local extension = Package("joy_mou")
extension.extensionName = "joy"

Fk:loadTranslationTable{
  ["joy_mou"] = "欢乐-谋",
  ["joy_mou2"] = "欢乐-谋",
}

local U = require "packages/utility/utility"

-- 谋开头武将





local joy_mouhuanggai = General(extension, "joy_mou__huanggai", "wu", 4)
local joy_mou__kurou = fk.CreateActiveSkill{
  name = "joy_mou__kurou",
  anim_type = "negative",
  card_num = 0,
  card_filter = Util.FalseFunc,
  target_num = 0,
  can_use = function(self, player)
    return player:usedSkillTimes(self.name, Player.HistoryPhase) == 0
  end,
  on_use = function(self, room, effect)
    local player = room:getPlayerById(effect.from)
    room:loseHp(player, 1, self.name)
    if player.dead then return end
    room:addPlayerMark(player, "@joy_mou__kurou")
    room:broadcastProperty(player, "MaxCards")
    room:changeMaxHp(player, 1)
  end
}
local joy_mou__kurou_maxcards = fk.CreateMaxCardsSkill{
  name = "#joy_mou__kurou_maxcards",
  correct_func = function(self, player)
    return player:getMark("@joy_mou__kurou")
  end,
}
joy_mou__kurou:addRelatedSkill(joy_mou__kurou_maxcards)
local joy_mou__kurou_delay = fk.CreateTriggerSkill{
  name = "#joy_mou__kurou_delay",
  frequency = Skill.Compulsory,
  mute = true,
  events = {fk.TurnStart, fk.HpRecover},
  can_trigger = function(self, event, target, player, data)
    if event == fk.TurnStart then
      return player == target and player:getMark("@joy_mou__kurou") > 0
    else
      return player == target and player:hasSkill(joy_mou__kurou)
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    if event == fk.TurnStart then
      local n = player:getMark("@joy_mou__kurou")
      room:setPlayerMark(player, "@joy_mou__kurou", 0)
      room:broadcastProperty(player, "MaxCards")
      room:changeMaxHp(player, -n)
    else
      room:notifySkillInvoked(player, "joy_mou__kurou", "special")
      player:setSkillUseHistory("joy_mou__kurou", 0, Player.HistoryPhase)
    end
  end,
}
joy_mou__kurou:addRelatedSkill(joy_mou__kurou_delay)
joy_mouhuanggai:addSkill(joy_mou__kurou)

local joy_mou__zhaxiang= fk.CreateTriggerSkill{
  name = "joy_mou__zhaxiang",
  anim_type = "drawcard",
  frequency = Skill.Compulsory,
  events = {fk.HpLost, fk.PreCardUse, fk.TurnEnd},
  can_trigger = function(self, event, target, player, data)
    if target == player and player:hasSkill(self) then
      if event == fk.HpLost then
        return true
      elseif event == fk.TurnEnd then
        return player:isWounded()
      else
        return data.card.trueName == "slash" and player:getMark("joy_mou__zhaxiang-turn") < ((player:getLostHp() + 1) // 2)
      end
    end
  end,
  on_trigger = function(self, event, target, player, data)
    local num = (event == fk.HpLost) and data.num or 1
    for i = 1, num do
      self:doCost(event, target, player, data)
      if player.dead then break end
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    if event == fk.HpLost then
      player:drawCards(3)
    elseif event == fk.TurnEnd then
      local x = (player:getLostHp() + 1) // 2
      player:drawCards(x)
    else
      data.extraUse = true
      data.disresponsiveList = table.map(player.room.alive_players, Util.IdMapper)
    end
  end,
  
  refresh_events = {fk.CardUsing, fk.HpChanged, fk.MaxHpChanged, fk.EventAcquireSkill, fk.TurnStart},
  can_refresh = function(self, event, target, player, data)
    if player:hasSkill(self, true) then
      if event == fk.CardUsing then
        return target == player and data.card.trueName == "slash"
      elseif event == fk.EventAcquireSkill then
        return target == player and data == self and player.room:getTag("RoundCount")
      elseif event == fk.TurnStart then
        return true
      else
        return target == player
      end
    end
  end,
  on_refresh = function(self, event, target, player, data)
    local room = player.room
    if event == fk.CardUsing then
      room:addPlayerMark(player, "joy_mou__zhaxiang-turn")
    elseif event == fk.EventAcquireSkill then
      room:setPlayerMark(player, "joy_mou__zhaxiang-turn", #room.logic:getEventsOfScope(GameEvent.UseCard, 1, function(e)
        local use = e.data[1]
        return use.from == player.id and use.card.trueName == "slash"
      end, Player.HistoryTurn))
    end
    local x = (player:getLostHp() + 1) // 2
    local used = player:getMark("joy_mou__zhaxiang-turn")
    room:setPlayerMark(player, "@joy_mou__zhaxiang-turn", used.."/"..x)
  end,
}
local joy_mou__zhaxiang_targetmod = fk.CreateTargetModSkill{
  name = "#joy_mou__zhaxiang_targetmod",
  bypass_times = function(self, player, skill, scope, card)
    return card and card.trueName == "slash" and player:hasSkill("joy_mou__zhaxiang")
    and player:getMark("joy_mou__zhaxiang-turn") < ((player:getLostHp() + 1) // 2)
  end,
  bypass_distances = function(self, player, skill, card)
    return card and card.trueName == "slash" and player:hasSkill("joy_mou__zhaxiang")
    and player:getMark("joy_mou__zhaxiang-turn") < ((player:getLostHp() + 1) // 2)
  end,
}
joy_mou__zhaxiang:addRelatedSkill(joy_mou__zhaxiang_targetmod)
joy_mouhuanggai:addSkill(joy_mou__zhaxiang)
Fk:loadTranslationTable{
  ["joy_mou"] = "欢乐谋",
  ["joy_mou__huanggai"] = "谋黄盖",

  ["joy_mou__kurou"] = "苦肉",
  [":joy_mou__kurou"] = "出牌阶段限一次，你可以失去一点体力并令体力上限和手牌上限增加1点直到下回合开始。当你回复体力后，此技能视为未发动。",
  ["@joy_mou__kurou"] = "苦肉",
  ["#joy_mou__kurou_delay"] = "苦肉",

  ["joy_mou__zhaxiang"] = "诈降",
  [":joy_mou__zhaxiang"] = "锁定技，①每当你失去一点体力后，摸三张牌；②回合结束时，你摸X张牌；③每回合你使用的前X张【杀】无距离和次数限制且无法响应（X为你已损失的体力值的一半，向上取整）。",
  ["@joy_mou__zhaxiang-turn"] = "诈降",
}

local machao = General:new(extension, "joy_mou__machao", "shu", 4)
local joy__yuma = fk.CreateTriggerSkill{
  name = "joy__yuma",
  anim_type = "drawcard",
  frequency = Skill.Compulsory,
  events = {fk.AfterCardsMove},
  can_trigger = function(self, event, target, player, data)
    if not player:hasSkill(self) then return end
    for _, move in ipairs(data) do
      if move.from == player.id then
        for _, info in ipairs(move.moveInfo) do
          if info.fromArea == Card.PlayerEquip and (Fk:getCardById(info.cardId).sub_type == Card.SubtypeDefensiveRide or Fk:getCardById(info.cardId).sub_type == Card.SubtypeOffensiveRide) then
            return true
          end
        end
      end
    end
  end,
  on_trigger = function(self, event, target, player, data)
    local n = 0
    for _, move in ipairs(data) do
      if move.from == player.id then
        for _, info in ipairs(move.moveInfo) do
          if info.fromArea == Card.PlayerEquip and (Fk:getCardById(info.cardId).sub_type == Card.SubtypeDefensiveRide or Fk:getCardById(info.cardId).sub_type == Card.SubtypeOffensiveRide) then
            n = n + 1
          end
        end
      end
    end
    for _ = 1, n do
      if  not player:hasSkill(self) then break end
      self:doCost(event, target, player, data)
    end
  end,
  on_use = function(self, event, target, player, data)
    player:drawCards(2, self.name)
  end,
}
local joy__yuma_distance = fk.CreateDistanceSkill{
  name = "#joy__yuma_distance",
  correct_func = function(self, from, to)
    if from:hasSkill(joy__yuma) then
      return -1
    end
  end,
}
joy__yuma:addRelatedSkill(joy__yuma_distance)
machao:addSkill(joy__yuma)
local tieji = fk.CreateTriggerSkill{
  name = "joy_mou__tieji",
  anim_type = "offensive",
  events = {fk.TargetSpecified},
  mute = true,
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(self) and data.to ~= player.id and
      data.card.trueName == "slash"
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    room:notifySkillInvoked(player, self.name)
    player:broadcastSkillInvoke("mou__tieji", 1)
    local to = room:getPlayerById(data.to)
    data.disresponsive = true
    room:addPlayerMark(to, "@@tieji-turn")
    room:addPlayerMark(to, MarkEnum.UncompulsoryInvalidity .. "-turn")
    local choices = U.doStrategy(room, player, to, {"tieji-zhiqu","tieji-raozheng"}, {"tieji-chuzheng","tieji-huwei"}, self.name, 1)
    local win = true
    if choices[1] == "tieji-zhiqu" and choices[2] ~= "tieji-chuzheng" then
      player:broadcastSkillInvoke("mou__tieji", 2)
      if not to:isNude() then
        local card = room:askForCardChosen(player, to, "he", self.name)
        room:obtainCard(player, card, false, fk.ReasonPrey)
      end
    elseif choices[1] == "tieji-raozheng" and choices[2] ~= "tieji-huwei" then
      player:broadcastSkillInvoke("mou__tieji", 3)
      player:drawCards(2, self.name)
    else
      win = false
      player:broadcastSkillInvoke("mou__tieji", 4)
    end
    if win then
      room:addPlayerMark(player, MarkEnum.SlashResidue.."-turn")
      if not player:isKongcheng() and #room:askForDiscard(player, 1, 1, false, self.name, true, ".", "#joy_mou__tieji-discard") > 0 then
        local ids = room:getCardsFromPileByRule("slash")
        if #ids > 0 then
          room:moveCardTo(ids, Card.PlayerHand, player, fk.ReasonPrey, self.name)
        end
      end
    end
  end,
}
machao:addSkill(tieji)
Fk:loadTranslationTable{
  ["joy_mou__machao"] = "谋马超",
  ["#joy_mou__machao"] = "阻戎负勇",
  ["joy__yuma"] = "驭马",
  [":joy__yuma"] = "锁定技，你计算与其他角色距离-1；每当你失去装备区一张坐骑牌后，你摸两张牌。",
  ["joy_mou__tieji"] = "铁骑",
  [":joy_mou__tieji"] = "每当你使用【杀】指定其他角色为目标后，你可令其不能响应此【杀】，且所有非锁定技失效直到回合结束。然后你与其进行谋弈：①“直取敌营”，你获得其一张牌；②“扰阵疲敌”，你摸两张牌。若你谋奕成功，本回合使用【杀】上次数限+1，且可以弃置一张手牌，获得一张【杀】。",
  ["#joy_mou__tieji-discard"] = "铁骑：可以弃置一张手牌，获得一张【杀】",
}

local mouhuangzhong = General(extension, "joy_mou__huangzhong", "shu", 4)
local mouliegongFilter = fk.CreateFilterSkill{
  name = "#joy_mou__liegong_filter",
  card_filter = function(self, card, player)
    return card.trueName == "slash" and
      card.name ~= "slash" and
      not player:getEquipment(Card.SubtypeWeapon) and
      player:hasSkill(self) and
      table.contains(player.player_cards[Player.Hand], card.id)
  end,
  view_as = function(self, card, player)
    local c = Fk:cloneCard("slash", card.suit, card.number)
    c.skillName = "joy_mou__liegong"
    return c
  end,
}
local mouliegongProhibit = fk.CreateProhibitSkill{
  name = "#joy_mou__liegong_prohibit",
  prohibit_use = function(self, player, card)
    if Fk.currentResponsePattern ~= "jink" or card.name ~= "jink" or player:getMark("joy_mou__liegong") == 0 then
      return false
    end
    if table.contains(player:getMark("joy_mou__liegong"), card:getSuitString(true)) then
      return true
    end
  end,
}
local mouliegong = fk.CreateTriggerSkill{
  name = "joy_mou__liegong",
  anim_type = "offensive",
  events = {fk.TargetSpecified},
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(self) and
      data.card.trueName == "slash" and
      #AimGroup:getAllTargets(data.tos) == 1 and
      player:getMark("@joy_mouliegongRecord") ~= 0
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local logic = room.logic
    local cardUseEvent = logic:getCurrentEvent().parent
    cardUseEvent.liegong_used = true

    local to = room:getPlayerById(data.to)
    local suits = player:getMark("@joy_mouliegongRecord")
    room:setPlayerMark(to, self.name, suits)

    if #suits > 1 then
      local cards = room:getNCards(#suits - 1)
      room:moveCardTo(cards, Card.Processing)
      data.additionalDamage = data.additionalDamage or 0
      for _, id in ipairs(cards) do
        if table.contains(suits, Fk:getCardById(id):getSuitString(true)) then
          room:setCardEmotion(id, "judgegood")
          data.additionalDamage = data.additionalDamage + 1
        else
          room:setCardEmotion(id, "judgebad")
        end
        room:delay(200)
      end
      if not player.dead then
        room:moveCardTo(cards, Card.PlayerHand, player, fk.ReasonPrey, self.name)
      end
    end
  end,

  refresh_events = {fk.TargetConfirmed, fk.CardUsing, fk.CardUseFinished},
  can_refresh = function(self, event, target, player, data)
    if not (target == player and player:hasSkill(self)) then return end
    local room = player.room
    if event == fk.CardUseFinished then
      return room.logic:getCurrentEvent().liegong_used
    else
      return data.card.suit ~= Card.NoSuit
    end
  end,
  on_refresh = function(self, event, target, player, data)
    local room = player.room
    if event == fk.CardUseFinished then
      room:setPlayerMark(player, "@joy_mouliegongRecord", 0)
      for _, p in ipairs(room:getAlivePlayers()) do
        room:setPlayerMark(p, "joy_mou__liegong", 0)
      end
    else
      local suit = data.card:getSuitString(true)
      local record = type(player:getMark("@joy_mouliegongRecord")) == "table" and player:getMark("@joy_mouliegongRecord") or {}
      table.insertIfNeed(record, suit)
      room:setPlayerMark(player, "@joy_mouliegongRecord", record)
    end
  end,
}
mouliegong:addRelatedSkill(mouliegongFilter)
mouliegong:addRelatedSkill(mouliegongProhibit)
mouhuangzhong:addSkill(mouliegong)
Fk:loadTranslationTable{
  ["joy_mou__huangzhong"] = "谋黄忠",
  ["#joy_mou__huangzhong"] = "没金铩羽",

  ["joy_mou__liegong"] = "烈弓",
  [":joy_mou__liegong"] = "若你未装备武器，你的【杀】只能当作普通【杀】使用或打出。"
   .. "你使用牌时或成为其他角色使用牌的目标后，若此牌的花色未被“烈弓”记录，"
   .. "则记录此种花色。当你使用【杀】指定唯一目标后，你可以亮出并获得牌堆顶的X张牌"
   .. "（X为你记录的花色数-1，且至少为0），然后每有一张牌花色与“烈弓”记录的"
   .. "花色相同，你令此【杀】伤害+1，且其不能使用“烈弓”记录花色的牌响应此"
   .. "【杀】。若如此做，此【杀】结算结束后，清除“烈弓”记录的花色。",

  ["@joy_mouliegongRecord"] = "烈弓",
  ["#joy_mou__liegong_filter"] = "烈弓",
}

local caocao = General(extension, "joy_mou__caocao", "wei", 4)
local mou__jianxiong = fk.CreateTriggerSkill{
  name = "joy_mou__jianxiong",
  anim_type = "masochism",
  events = {fk.Damaged},
  can_trigger = function(self, event, target, player, data)
     return target == player and player:hasSkill(self) and ((data.card and target.room:getCardArea(data.card) == Card.Processing) or 2 - player:getMark("@joy_mou__jianxiong") > 0)
  end,
  on_use = function(self, event, target, player, data)
    if data.card and target.room:getCardArea(data.card) == Card.Processing then
      player.room:obtainCard(player.id, data.card, true, fk.ReasonJustMove)
    end
    local num = 2 - player:getMark("@joy_mou__jianxiong")
    if num > 0 then
      player:drawCards(num, self.name)
    end
    local choices = {"getMark"}
    local n = "#joy_mou__jianxiong-getMark"
      if player:getMark("@joy_mou__jianxiong") ~= 0 then
        table.insert(choices,"removeMark")
        n = "#joy_mou__jianxiong-choose"
      end
    if player.room:askForSkillInvoke(player, self.name, nil, n) then
      local choice = player.room:askForChoice(player,choices,self.name)
      if choice == "getMark" then
        player.room:addPlayerMark(player,  "@joy_mou__jianxiong", 1)
      else
        player.room:removePlayerMark(player, "@joy_mou__jianxiong", 1)
      end
    end
  end,
}
local mou__jianxiong_gamestart = fk.CreateTriggerSkill{
  name = "#joy_mou__jianxiong_gamestart",
  events = {fk.GameStart},
  can_trigger = function(self, event, target, player, data)
    return player:hasSkill("joy_mou__jianxiong")
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    player:broadcastSkillInvoke("joy_mou__jianxiong")
    local choice = room:askForChoice(player, {"0", "1", "2"}, "joy_mou__jianxiong", "#joy_mou__jianxiong-choice")
    room:addPlayerMark(player,  "@joy_mou__jianxiong", tonumber(choice))
  end,
}
local mou__qingzheng = fk.CreateActiveSkill{
  name = "joy_mou__qingzheng",
  anim_type = "control",
  target_num = 0,
  can_use = function(self, player)
    return player:usedSkillTimes(self.name, Player.HistoryPhase) == 0
  end,
  target_filter = Util.FalseFunc,
  on_use = function(self, room, effect)
    local player = room:getPlayerById(effect.from)
    local num = math.max(3 - player:getMark("@joy_mou__jianxiong"),0)
    local cards ={}
    if num > 0 then
    local suits = {"diamond","heart","club","spade"}
    local choices = room:askForChoices(player, suits, num, num, self.name, "#joy_mou__qingzheng-choice:::"..num,false)
    
    for _, ch in ipairs(choices) do
      for _, c in ipairs(player.player_cards[Player.Hand]) do
        local suit = Fk:getCardById(c):getSuitString()
        if suit == ch then
          table.insertIfNeed(cards, c)
        end
      end
    end
    cards = table.filter(cards, function (id)
      return not player:prohibitDiscard(Fk:getCardById(id))
    end)
    if #cards > 0 then
      room:throwCard(cards, self.name, player)
    end
    end
    if player.dead then return end
    local tars = {}
    for _, p in ipairs(room:getOtherPlayers(player)) do
      if not p:isKongcheng() then
        table.insertIfNeed(tars,p.id)
      end
    end
    if #tars <= 0 then return end
    local tar = room:askForChoosePlayers(player,tars,1,1,"清正：选择一名其他角色，观看其手牌并弃置其中一个花色的所有牌。",self.name,true)
    if #tar <= 0 then return end
    local to = room:getPlayerById(tar[1])
    local cids = to.player_cards[Player.Hand]
    local id1 = room:askForCardChosen(player, to, { card_data = { { "$Hand", cids }  } }, self.name, "#joy_mou__qingzheng-throw")
    local cards1 = table.filter(cids, function(id) return Fk:getCardById(id).suit == Fk:getCardById(id1).suit end)
    room:throwCard(cards1, self.name, to, player)
    if #cards > #cards1 and not to.dead then
      room:damage{ from = player, to = to, damage = 1, skillName = self.name }
    end
    if not player.dead then
      local choices = {"getMark"}
      local n = "#joy_mou__jianxiong-getMark"
      if player:getMark("@joy_mou__jianxiong") ~= 0 then
        table.insert(choices,"removeMark")
        n = "#joy_mou__jianxiong-choose"
      end
      if player.room:askForSkillInvoke(player, self.name, nil, n) then
        local choice = player.room:askForChoice(player,choices,self.name)
        if choice == "getMark" then
          player.room:addPlayerMark(player,  "@joy_mou__jianxiong", 1)
        else
          player.room:removePlayerMark(player, "@joy_mou__jianxiong", 1)
        end
      end
    end
  end,
}
mou__jianxiong:addRelatedSkill(mou__jianxiong_gamestart)
caocao:addSkill(mou__jianxiong)
caocao:addSkill(mou__qingzheng)
caocao:addSkill("mou__hujia")

Fk:loadTranslationTable{
  ["joy_mou__caocao"] = "谋曹操",
  ["#joy_mou__caocao"] = "魏武大帝",

  ["joy_mou__jianxiong"] = "奸雄",
  ["#joy_mou__jianxiong_gamestart"] = "奸雄",
  [":joy_mou__jianxiong"] = "游戏开始时，你可以获得至多两枚“治世”标记。当你受到伤害后，你可以获得对你造成伤害的牌并摸2-X张牌，然后你可以增减1枚“治世”。"..
  "（X为“治世”的数量）。",
  ["joy_mou__qingzheng"] = "清正",
  [":joy_mou__qingzheng"] = "出牌阶段限一次，你可以弃置自己3-X（X为你的“治世”标记数）种花色的所有手牌，然后可以选择一名有手牌的其他角色，观看其手牌并选择一种"..
  "花色的牌，其弃置所有该花色的手牌。若如此做且其弃置的手牌小于你以此法弃置的牌数，你对其造成1点伤害，然后你可以增减一枚“治世”。",

  ["#joy_mou__jianxiong-choose"] = "是否选择增减一枚“治世”标记？",
  ["#joy_mou__jianxiong-getMark"] = "是否增加一枚“治世”标记？",
  ["#joy_mou__jianxiong-choice"] = "奸雄：请选择要获得的“治世”标记数量。",
  ["#joy_mou__qingzheng-choice"] = "清正：选择 %arg 个花色并弃置所有对应花色的手牌",
  ["#joy_mou__qingzheng-discard"] = "清正：请选择一种花色的所有牌弃置，总共%arg 次 现在是第%arg2 次",
  ["#joy_mou__qingzheng-throw"] = "清正：弃置其中一种花色的所有手牌",
  ["@joy_mou__jianxiong"] = "治世",

  ["getMark"] = "增加一枚标记",
  ["removeMark"] = "减少一枚标记",

}

local liubei = General(extension, "joy_mou__liubei", "shu", 4)
local rende = fk.CreateViewAsSkill{
  pattern = ".",
  name = "joy_mou__rende",
  interaction = function()
    local choices = {}
    if Self:getMark("@joy_mou__rende") > 1 and Self:getMark("joy_mou__rende_vs-turn") == 0 then
      for _, name in ipairs(U.getAllCardNames("bt")) do
        local card = Fk:cloneCard(name)
        if (Fk.currentResponsePattern == nil and Self:canUse(card)) or
        (Fk.currentResponsePattern and Exppattern:Parse(Fk.currentResponsePattern):match(card)) then
          if (card.type == Card.TypeBasic and Self:getMark("@joy_mou__rende") > 1)
          or (card:isCommonTrick() and Self:getMark("@joy_mou__rende") > 2) then
            table.insertIfNeed(choices, card.name)
          end
        end
      end
    end
    return UI.ComboBox {choices = choices}
  end,
  view_as = function(self)
    if not self.interaction.data then return nil end
    local c = Fk:cloneCard(self.interaction.data)
    c.skillName = self.name
    return c
  end,
  before_use = function(self, player, use)
    local room = player.room
    room:removePlayerMark(player, "@joy_mou__rende", use.card.type == Card.TypeBasic and 2 or 3)
    room:setPlayerMark(player, "joy_mou__rende_used-turn", 1)
  end,
  enabled_at_play = function(self, player)
    return player:getMark("@joy_mou__rende") > 1 and player:getMark("joy_mou__rende_prohibit-turn") == 0
    and player:getMark("joy_mou__rende_used-turn") == 0
  end,
  enabled_at_response = function (self, player, response)
    return player:getMark("@joy_mou__rende") > 1 and player:getMark("joy_mou__rende_prohibit-turn") == 0
    and player:getMark("joy_mou__rende_used-turn") == 0
  end,
}
-- FIXME : use skill_card to connet activeSkill and viewasSkill
local rende_give = fk.CreateActiveSkill{
  name = "joy_mou__rende&",
  main_skill = rende,
  prompt = "#joy_mou__rende-give",
  target_num = 1,
  min_card_num = 1,
  card_filter = Util.TrueFunc,
  target_filter = function(self, to_select, selected, selected_cards)
    return #selected == 0 and to_select ~= Self.id and #selected_cards > 0
    and Fk:currentRoom():getPlayerById(to_select):getMark("joy_mou__rende_target-phase") == 0
  end,
  on_use = function(self, room, effect)
    local player = room:getPlayerById(effect.from)
    local target = room:getPlayerById(effect.tos[1])
    room:setPlayerMark(target, "joy_mou__rende_target-phase", 1)
    room:setPlayerMark(target, "joy_mou__rende_target", 1)
    room:moveCardTo(effect.cards, Player.Hand, target, fk.ReasonGive, self.name, nil, false, player.id)
    if player.dead then return end
    room:setPlayerMark(player, "@joy_mou__rende", math.min(10, player:getMark("@joy_mou__rende") + #effect.cards))
  end,
  can_use = function (self, player, card)
    return player:getMark("joy_mou__rende_prohibit-turn") == 0
  end,
}
local rende_trigger = fk.CreateTriggerSkill{
  name = "#joy_mou__rende_trigger",
  mute = true,
  main_skill = rende,
  events = {fk.EventPhaseStart},
  can_trigger = function(self, event, target, player, data)
    return player:hasSkill(rende) and target == player and player.phase == Player.Play and player:getMark("@joy_mou__rende") < 10
  end,
  on_cost = Util.TrueFunc,
  on_use = function(self, event, target, player, data)
    local room = player.room
    player:broadcastSkillInvoke("joy_mou__rende")
    room:setPlayerMark(player, "@joy_mou__rende", math.min(10, player:getMark("@joy_mou__rende") + 3))
  end,
}
rende:addRelatedSkill(rende_give)
rende:addRelatedSkill(rende_trigger)
liubei:addSkill(rende)
local zhangwu = fk.CreateActiveSkill{
  name = "joy_mou__zhangwu",
  anim_type = "control",
  frequency = Skill.Limited,
  can_use = function(self, player)
    return player:usedSkillTimes(self.name, Player.HistoryGame) == 0
  end,
  card_num = 0,
  card_filter = function() return false end,
  target_num = 0,
  on_use = function(self, room, effect)
    local player = room:getPlayerById(effect.from)
    local x = math.min(3, (room:getTag("RoundCount") - 1))
    if x > 0 then
      for _, p in ipairs(room:getOtherPlayers(player)) do
        if player.dead then break end
        if not p.dead and p:getMark("joy_mou__rende_target") > 0 and not p:isNude() then
          local cards = (#p:getCardIds("he") < x) and p:getCardIds("he") or
          room:askForCard(p, x, x, true, self.name, false, ".", "#mou__zhangwu-give::"..player.id..":"..x)
          if #cards > 0 then
            local dummy = Fk:cloneCard("dilu")
            dummy:addSubcards(cards)
            room:obtainCard(player, dummy, false, fk.ReasonGive)
          end
        end
      end
    end
    if not player.dead and player:isWounded() then
      room:recover { num = math.min(3,player.maxHp-player.hp), skillName = self.name, who = player, recoverBy = player}
    end
    room:setPlayerMark(player, "joy_mou__rende_prohibit-turn", 1)
  end,
}
liubei:addSkill(zhangwu)
local joy_mou__jijiang = fk.CreateTriggerSkill{
  name = "joy_mou__jijiang$",
  anim_type = "offensive",
  events = {fk.EventPhaseEnd},
  can_trigger = function(self, event, target, player, data)
    if target == player and player:hasSkill(self) and player.phase == Player.Play then
      local players = player.room.alive_players
      return #players > 2 and table.find(players, function(p) return p ~= player and p.kingdom == "shu" end)
    end
  end,
  on_cost = function (self, event, target, player, data)
    local room = player.room
    local success, dat = room:askForUseActiveSkill(player, "joy_mou__jijiang_choose", "#joy_mou__jijiang-promot", true, nil, true)
    if success and dat then
      self.cost_data = dat.targets
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local victim = room:getPlayerById(self.cost_data[1])
    local bro = room:getPlayerById(self.cost_data[2])
    room:doIndicate(player.id, {bro.id})
    local choices = {"joy_mou__jijiang_skip"}
    if not bro:prohibitUse(Fk:cloneCard("slash")) and not bro:isProhibited(victim, Fk:cloneCard("slash")) then
      table.insert(choices, 1, "joy_mou__jijiang_slash:"..victim.id)
    end
    if room:askForChoice(bro, choices, self.name) == "joy_mou__jijiang_skip" then
      room:setPlayerMark(bro, "@@joy_mou__jijiang_skip", 1)
    else
      room:useVirtualCard("slash", nil, bro, victim, self.name, true)
    end
  end,
}
local joy_mou__jijiang_choose = fk.CreateActiveSkill{
  name = "joy_mou__jijiang_choose",
  card_num = 0,
  target_num = 2,
  card_filter = Util.FalseFunc,
  target_filter = function(self, to_select, selected)
    if #selected > 1 or to_select == Self.id then return false end
    if #selected == 0 then
      return true
    else
      local victim = Fk:currentRoom():getPlayerById(selected[1])
      local bro = Fk:currentRoom():getPlayerById(to_select)
      return bro.kingdom == "shu" and bro:inMyAttackRange(victim)
    end
  end,
}
Fk:addSkill(joy_mou__jijiang_choose)
local joy_mou__jijiang_delay = fk.CreateTriggerSkill{
  name = "#joy_mou__jijiang_delay",
  events = {fk.EventPhaseChanging},
  priority = 10,
  mute = true,
  can_trigger = function(self, event, target, player, data)
    return target:getMark("@@joy_mou__jijiang_skip") > 0 and data.to == Player.Play
  end,
  on_cost = Util.TrueFunc,
  on_use = function(self, event, target, player, data)
    player.room:setPlayerMark(target, "@@joy_mou__jijiang_skip", 0)
    target:skip(Player.Play)
    return true
  end,
}
joy_mou__jijiang:addRelatedSkill(joy_mou__jijiang_delay)
liubei:addSkill(joy_mou__jijiang)
Fk:loadTranslationTable{
  ["joy_mou__liubei"] = "谋刘备",
  ["#joy_mou__liubei"] = "雄才盖世",
  ["joy_mou__rende"] = "仁德",
  [":joy_mou__rende"] = "①出牌阶段开始时，你获得3个“仁”标记；②出牌阶段，你可以将任意张牌交给一名本阶段未以此法获得牌的其他角色，获得等量的“仁”标记(至多拥有10个)。③每回合限一次，每当你需要使用或打出基本牌/普通锦囊牌时，你可以移去2/3个“仁”标记视为使用或打出之。",
  ["@joy_mou__rende"] = "仁",
  ["joy_mou__rende&"] = "仁德",
  ["#joy_mou__rende-give"] = "仁德：将任意张牌交给一名本阶段未以此法获得牌的其他角色，获得等量的“仁”标记",
  [":joy_mou__rende&"] = "出牌阶段，你可以将任意张牌交给一名本阶段未以此法获得牌的其他角色，获得等量的“仁”标记(至多拥有10个)。",
  ["joy_mou__zhangwu"] = "章武",
  [":joy_mou__zhangwu"] = "限定技，出牌阶段，你可以令〖仁德〗选择过的所有角色依次交给你X张牌（X为游戏轮数-1，至多为3），然后你回复3点体力，无法发动〖仁德〗直到回合结束。",
  ["joy_mou__jijiang"] = "激将",
  [":joy_mou__jijiang"] = "主公技，出牌阶段结束时，你可以选择一名其他角色，然后令一名攻击范围内含有其的其他蜀势力角色选择一项："..
  "1.视为对其使用一张【杀】；2.跳过下一个出牌阶段。",
  ["@@joy_mou__jijiang_skip"] = "激将",
  ["#joy_mou__jijiang-promot"] = "激将：先选择【杀】的目标，再选需要响应“激将”的蜀势力角色",
  ["joy_mou__jijiang_slash"] = "视为对 %src 使用一张【杀】",
  ["joy_mou__jijiang_skip"] = "跳过下一个出牌阶段",
  ["joy_mou__jijiang_choose"] = "激将",
}

local zhaoyun = General(extension, "joy_mou__zhaoyun", "shu", 4)
local longdan = fk.CreateViewAsSkill{
  name = "joy_mou__longdan",
  pattern = ".|.|.|.|.|basic",
  prompt = "#joy_mou__longdan",
  interaction = function()
    local names = {}
    for _, id in ipairs(Fk:getAllCardIds()) do
      local card = Fk:getCardById(id)
      if card.type == Card.TypeBasic and not card.is_derived and
        ((Fk.currentResponsePattern == nil and card.skill:canUse(Self, card)) or
        (Fk.currentResponsePattern and Exppattern:Parse(Fk.currentResponsePattern):match(card))) then
        table.insertIfNeed(names, card.name)
      end
    end
    if #names == 0 then return end
    return UI.ComboBox {choices = names}
  end,
  card_filter = function(self, to_select, selected)
    if #selected == 0 then
      return Fk:getCardById(to_select).type == Card.TypeBasic
    end
    if #selected == 1 then return false end
  end,
  view_as = function(self, cards)
    if not self.interaction.data then return end
    if #cards ~= 1 then return end
    if not table.find(cards, function(id) return Fk:getCardById(id).type == Card.TypeBasic end) then return end
    local card = Fk:cloneCard(self.interaction.data)
    card:addSubcards(cards)
    card.skillName = self.name
    return card
  end,
  before_use = function(self, player, use)
    player.room:removePlayerMark(player,"@joy_mou__longdan",1)
    if not player.dead then
      player:drawCards(1, self.name)
    end
  end,
  enabled_at_play = function(self, player)
    return player:getMark("@joy_mou__longdan") > 0 
  end,
  enabled_at_response = function(self, player, response)
    return player:getMark("@joy_mou__longdan") > 0 
  end,
}
local longdan_trigger = fk.CreateTriggerSkill{
  name = "#joy_mou__longdan_trigger",
  anim_type = "offensive",
  events = {fk.GameStart,fk.TurnEnd},
  can_trigger = function(self, event, target, player, data)
      return player:hasSkill(self) and player:getMark("@joy_mou__longdan") < 3
    
  end,
  on_cost = Util.TrueFunc,
  on_use = function (self, event, target, player, data)
      if player:getMark("@joy_mou__longdan") < 3 and not player.dead then
        player.room:addPlayerMark(player,"@joy_mou__longdan",1)
      end
  end
}
local shilve = fk.CreateTriggerSkill{
  name = "joy_mou__shilve",
  anim_type = "offensive",
  events = {fk.CardUsing, fk.CardResponding},
  can_trigger = function(self, event, target, player, data)
    if target == player and player:hasSkill(self) and (data.card.trueName == "slash" or data.card.name == "jink" ) and
      table.find(data.card.skillNames, function(name) return string.find(name, "joy_mou__longdan") end) then
      local id
      if event == fk.CardUsing then
        if data.card.trueName == "slash" then
          id = data.tos[1][1]
        elseif data.card.name == "jink" then
          if data.responseToEvent then
            id = data.responseToEvent.from  --jink
          end
        end
      elseif event == fk.CardResponding then
        if data.responseToEvent then
          if data.responseToEvent.from == player.id then
            id = data.responseToEvent.to 
          else
            id = data.responseToEvent.from 

          end
        end
      end
      if id ~= nil then
        self.cost_data = id
        return true
      end
    end
  end,
  on_cost = function(self, event, target, player, data)
    return player.room:askForSkillInvoke(player, self.name, nil, "#joy_mou__shilve-invoke::"..self.cost_data)
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local to = room:getPlayerById(self.cost_data)
    local choices = U.doStrategy(room, player, to, {"joy__shilve-yanqi","joy__shilve-danzhuang"}, {"joy__shilve-yanqi2","joy__shilve-danzhuang2"}, self.name, 1)
    local win = true
    if choices[1] == "joy__shilve-yanqi" and choices[2] ~= "joy__shilve-yanqi2" then
      player:broadcastSkillInvoke("joy_mou__shilve", 2)
      local cards = room:getCardsFromPileByRule(".|.|.|.|.|^basic")
      if #cards > 0 and not player.dead then
        local get = cards[1]
        room:obtainCard(player, get, false, fk.ReasonDraw)
      end
    elseif choices[1] == "joy__shilve-danzhuang" and choices[2] ~= "joy__shilve-danzhuang2" and player:getMark("@joy_mou__longdan") < 3 then
      player:broadcastSkillInvoke("joy_mou__shilve", 3)
      room:addPlayerMark(player,"@joy_mou__longdan",1)
    else
      win = false
      player:broadcastSkillInvoke("joy_mou__shilve", 4)
    end

  end,
}
longdan:addRelatedSkill(longdan_trigger)
zhaoyun:addSkill(longdan)
zhaoyun:addSkill(shilve)
Fk:loadTranslationTable{
  ["joy_mou__zhaoyun"] = "谋赵云",
  
  ["joy_mou__longdan"] = "龙胆",
  [":joy_mou__longdan"] = "剩余可用X次（X初始为1且最大为3，每名角色回合结束后X加1），你可以将一张基本牌当做任意基本牌使用或打出，若如此做，你摸一张牌。",
  ["@joy_mou__longdan"] = "龙胆",
  ["#joy_mou__longdan_trigger"] = "龙胆",
  ["#joy_mou__longdan"] = "龙胆：你可以将一张基本牌当任意基本牌使用或打出",
  ["joy_mou__shilve"] = "识略",
  [":joy_mou__shilve"] = "当你发动〖龙胆〗使用或打出【杀】，【闪】时，你可与对方进行谋奕："..
  "<br>①偃旗息鼓：获得一张非基本牌；"..
  "<br>②胆壮心雄：增加1次〖龙胆〗次数。",

  ["#joy_mou__shilve-invoke"] = "是否发动〖识略〗与 %dest 进行谋奕？",
  ["joy__shilve-yanqi"] = "偃旗息鼓",
  [":joy__shilve-yanqi"] = "获得一张非基本牌",
  ["joy__shilve-danzhuang"] = "胆壮心雄",
  [":joy__shilve-danzhuang"] = "增加1次〖龙胆〗次数。",
  ["joy__shilve-yanqi2"] = "偃旗息鼓",
  [":joy__shilve-yanqi2"] = "防止对方获得一张非基本牌",
  ["joy__shilve-danzhuang2"] = "胆壮心雄",
  [":joy__shilve-danzhuang2"] = "防止对方增加1次〖龙胆〗次数。"
}

local lvmeng = General(extension, "joy_mou__lvmeng", "wu", 4)
local duojing = fk.CreateActiveSkill{
  name = "joy_mou__duojing",
  anim_type = "control",
  card_num = 0,
  min_target_num = 1,
  max_target_num = 1,
  can_use = function(self, player)
    return player:usedSkillTimes(self.name, Player.HistoryPhase) < 2 
  end,
  card_filter = Util.FalseFunc,
  target_filter = function(self, to_select, selected)
      return to_select ~= Self.id
  end,
  on_use = function(self, room, effect)
    local player = room:getPlayerById(effect.from)
    local to = room:getPlayerById(effect.tos[1])
    local choices = U.doStrategy(room, player, to, {"joy__duojing-xiuyang","joy__duojing-baiyi"}, {"joy__duojing-xiuyang2","joy__duojing-baiyi2"}, self.name, 1)
    local win = true
    if choices[1] == "joy__duojing-xiuyang" and choices[2] ~= "joy__duojing-xiuyang2" then
      player:broadcastSkillInvoke("joy_mou__shilve", 2)
      if not to:isNude() then
        room:doIndicate(player.id, {to.id})
        local card = room:askForCardChosen(player, to, "he", self.name)
        room:obtainCard(player, card, false, fk.ReasonPrey)
      end
      if not player.dead then
        player.room:recover({
          who = player,
          num = 1,
          recoverBy = player,
          skillName = self.name
          })
      end
      local n = player.maxHp - player.hp
      if not player.dead and n > 0 and room:askForSkillInvoke(player,self.name,".","#joy_mou__duojing-zhiheng:::"..n) then
        player:drawCards(n,self.name)
        if not player.dead then
          room:askForDiscard(player,n,n)
        end
      end
    elseif choices[1] == "joy__duojing-baiyi" and choices[2] ~= "joy__duojing-baiyi2" then
      room:addPlayerMark(to, fk.MarkArmorNullified)
      room:useVirtualCard("slash", nil, player, to, self.name,true)
      room:removePlayerMark(to, fk.MarkArmorNullified)
      room:addPlayerMark(player, MarkEnum.SlashResidue.."-turn")
      room:setPlayerMark(player,"joy__keji-turn",1)
    end
  end,
}
lvmeng:addSkill("joy__keji")
lvmeng:addSkill(duojing)
Fk:loadTranslationTable{
  ["joy_mou__lvmeng"] = "谋吕蒙",

  ["joy_mou__duojing"] = "夺荆",
  [":joy_mou__duojing"] = "出牌阶段限两次，你可以与一名其他角色进行“谋弈”："..
  "<br>①休养生息：获得目标角色一张牌并回复一点体力，然后你可以摸X张牌，并弃置等量的牌。（X为已损失体力值）"..
  "<br>②白衣渡江：视为对目标使用一张不计次数且无视距离和防具的【杀】，然后本回合可额外使用一次【杀】，且使用或打出过的【杀】不影响〖克己〗。",
  ["joy__duojing-xiuyang"] = "休养生息",
  [":joy__duojing-xiuyang"] = "获得目标角色一张牌并回复一点体力，然后你可以摸X张牌，并弃置等量的牌。（X为已损失体力值)",
  ["joy__duojing-baiyi"] = "白衣渡江",
  [":joy__duojing-baiyi"] = "视为对目标使用一张不计次数且无视距离和防具的【杀】，然后本回合可额外使用一次【杀】，且使用或打出过的【杀】不影响〖克己〗。",
  ["joy__duojing-xiuyang2"] = "休养生息",
  [":joy__duojing-xiuyang2"] = "防止对方获得你的一张牌并回复一点体力，然后其可以摸X张牌，并弃置等量的牌。（X为已损失体力值)",
  ["joy__duojing-baiyi2"] = "白衣渡江",
  [":joy__duojing-baiyi2"] = "视为对方对你使用一张不计次数且无视距离和防具的【杀】，然后其本回合可额外使用一次【杀】，且使用或打出过的【杀】不影响〖克己〗。",
  ["#joy_mou__duojing-zhiheng"] = "夺荆：你可以摸 %arg 张牌，然后弃置等量张牌",

}

local mouyuanshao = General(extension, "joy_mou__yuanshao", "qun", 4)
local mou__luanji = fk.CreateViewAsSkill{
  name = "joy_mou__luanji",
  anim_type = "offensive",
  pattern = "archery_attack",
  prompt = "#mou__luanji-viewas",
  enabled_at_play = function(self, player)
    return true
  end,
  card_filter = function(self, to_select, selected)
    if #selected == 2 or Fk:currentRoom():getCardArea(to_select) ~= Player.Hand then return false end
    local record = type(Self:getMark("@joymou__luanji-turn")) == "table" and Self:getMark("@joymou__luanji-turn") or {}
    return not table.contains(record, Fk:getCardById(to_select):getColorString())
  end,
  view_as = function(self, cards)
    if #cards == 2 then
      local archery_attack = Fk:cloneCard("archery_attack")
      archery_attack:addSubcards(cards)
      return archery_attack
    end
  end,
  before_use = function(self, player, use)
    local room = player.room
    local record = type(player:getMark("@joymou__luanji-turn")) == "table" and player:getMark("@joymou__luanji-turn") or {}
    local cards = use.card.subcards
    for _, cid in ipairs(cards) do
      local color = Fk:getCardById(cid):getColorString()
      if color ~= "nocolor" then table.insertIfNeed(record, color) end
    end
    room:setPlayerMark(player, "@joymou__luanji-turn", record)
  end
}
local mou__luanji_trigger = fk.CreateTriggerSkill{
  name = "#joy_mou__luanji_trigger",
  anim_type = "drawcard",
  events = {fk.CardResponding,fk.Damage},
  can_trigger = function(self, event, target, player, data)
    if event == fk.CardResponding and player:hasSkill(mou__luanji) and player:getMark("joy_mou__luanjidraw-turn") < 3 and data.card.name == "jink" then
      return data.responseToEvent and
      data.responseToEvent.card.name =="archery_attack"
    elseif player:hasSkill(mou__luanji) and player:getMark("joy_mou__luanjidiscard-turn") < 3 and data.card then
      return target == player and
      data.card.name =="archery_attack" and not data.to.dead  and not data.to:isNude()
    end
  end,
  on_cost = function(self, event, target, player, data)
    if event == fk.CardResponding then return true end
    local room = player.room
    return room:askForSkillInvoke(player,self.name,".","#joy_mou__luanjidiscard::"..data.to.id)
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    if event == fk.CardResponding and not player.dead then
      player:broadcastSkillInvoke(mou__luanji.name)
      player:drawCards(1, self.name)
      room:addPlayerMark(player,"joy_mou__luanjidraw-turn",1)
    else
      local card = room:askForCardChosen(player,data.to,"he",self.name,"#joy_mou__luanjidiscardchosen")
      if card > 0 then
        room:throwCard(card,self.name,data.to,player)
        room:addPlayerMark(player,"joy_mou__luanjidiscard-turn",1)
      end
    end
  end,
}
local mou__xueyi = fk.CreateTriggerSkill{
  name = "joy_mou__xueyi$",
  anim_type = "drawcard",
  events = {fk.TargetSpecified},
  frequency = Skill.Compulsory,
  can_trigger = function(self, event, target, player, data)
    return player:hasSkill(self) and target == player and player:usedSkillTimes(self.name) < 2 and
    data.to ~= player.id and player.room:getPlayerById(data.to).kingdom == "qun"
  end,
  on_use = function(self, event, target, player, data)
    player:drawCards(1, self.name)
  end,
}
local mou__xueyi_maxcards = fk.CreateMaxCardsSkill{
  name = "#joy_mou__xueyi_maxcards",
  correct_func = function(self, player)
    if player:hasSkill(mou__xueyi) then
      local hmax = 0
      for _, p in ipairs(Fk:currentRoom().alive_players) do
        if  p.kingdom == "qun" then
          hmax = hmax + 1
        end
      end
      return hmax *2
    else
      return 0
    end
  end,
}
mou__luanji:addRelatedSkill(mou__luanji_trigger)
mou__xueyi:addRelatedSkill(mou__xueyi_maxcards)
mouyuanshao:addSkill(mou__luanji)
mouyuanshao:addSkill(mou__xueyi)
Fk:loadTranslationTable{
  ["joy_mou__yuanshao"] = "谋袁绍",
  ["joy_mou__luanji"] = "乱击",
  [":joy_mou__luanji"] = "出牌阶段，你可以将两张手牌当【万箭齐发】使用（不能使用本回合以此法使用过的颜色）；"..
  "<br>当其他角色打出【闪】响应【万箭齐发】时，你摸一张牌（每回合你以此法至多获得三张牌）。"..
  "<br>当有角色受到你的【万箭齐发】造成的伤害后，你可以弃置其一张牌（每回合限3次）。",
  ["joy_mou__xueyi"] = "血裔",
  [":joy_mou__xueyi"] = "主公技，锁定技，你的手牌上限+2X（X为群势力角色数）；"..
  "当你使用牌指定其他群势力角色为目标后，你摸一张牌（每回合你以此法至多获得两张牌）。",

  ["#joy_mou__luanjidiscard"] = "乱击：你可以弃置 %dest 一张牌",
  ["#joy_mou__luanjidiscardchosen"] = "乱击:选择一张牌弃置之",
  ["#joy_mou__luanji_trigger"] = "乱击",
  ["@joymou__luanji-turn"] = "乱击",

  ["$joy_mou__luanji1"] = " ",
  ["$joy_mou__luanji2"] = " ",
  ["$joy_mou__xueyi1"] = " ",
  ["$joy_mou__xueyi2"] = " ",
  ["~joy_mou__yuanshao"] = " ",
}

local mouyujin = General(extension, "joy_mou__yujin", "wei", 4)
local jieyue = fk.CreateTriggerSkill{
  name = "joy_mou__jieyue",
  anim_type = "control",
  events = {fk.EventPhaseStart},
  can_trigger = function (self, event, target, player, data)
    return player:hasSkill(self) and target == player and player.phase == Player.Start
  end,
  on_cost = function(self, event, target, player, data)
    local _, dat = player.room:askForUseActiveSkill(player, "joy_mou__jieyue_active", "#joy_mou__jieyue-invoke", true)
    if dat then
      self.cost_data = dat
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local targetid = self.cost_data.targets
    local choice = self.cost_data.interaction
    local junling = false
    local target = room:getPlayerById(targetid[1])
    if not target.dead then
      room:drawCards(target,1,self.name)
    end
    if target.dead or player.dead then return false end
    if choice == "joy__jieyue1" then
      local to = room:askForChoosePlayers(player,table.map(room.alive_players, Util.IdMapper),1,1,"#joy__jieyue1-choose",self.name,false)
      if #to > 0 then
        if room:askForSkillInvoke(target,self.name,data,"#joy__junling1::"..to[1]) then
          room:damage({
            from = target,
            to = room:getPlayerById(to[1]),
            damage = 1,
            skillName = self.name,
          })
          junling = true
        end
      end
    elseif choice == "joy__jieyue2" then
      if room:askForSkillInvoke(target,self.name,data,"#joy__junling2") then
        local cards1 = target.player_cards[Player.Hand]
        local cards2 = target.player_cards[Player.Equip]
        if #cards1 > 0 then
          room:throwCard(table.random(cards1),self.name,target)
        end
        if #cards2 > 0 then
          room:throwCard(table.random(cards2),self.name,target)
        end
        junling = true
      end
    elseif choice == "joy__jieyue3" then
      if room:askForSkillInvoke(target,self.name,data,"#joy__junling3") then
        room:setPlayerMark(target,"@@joy__jieyuerecover-turn",1)
        junling = true
      end
    elseif choice == "joy__jieyue4" then
      if room:askForSkillInvoke(target,self.name,data,"#joy__junling4") then
        room:setPlayerMark(target,"@@joy__jieyuecard-turn",1)
        room:addPlayerMark(target, MarkEnum.UncompulsoryInvalidity .. "-turn")
        junling = true
      end
    end
    if not junling and not player.dead then
      player:drawCards(3,self.name)
      room:setPlayerMark(target,"@@joy__jieyuedamage-turn",1)
    elseif not player.dead then
      player:drawCards(1,self.name)
    end
  end,
}
local jieyue_active = fk.CreateActiveSkill{
  name = "joy_mou__jieyue_active",
  card_num = 0,
  target_num = 1,
  interaction = function()
    return UI.ComboBox {choices = {"joy__jieyue1","joy__jieyue2","joy__jieyue3","joy__jieyue4"}}
  end,
  card_filter = Util.FalseFunc,
  target_filter = function (self,to_select)
    return to_select ~= Self.id
  end
}
local jieyue_trigger = fk.CreateTriggerSkill{
  name = "#joy_mou__jieyue_trigger",
  mute = true,
  events = {fk.PreHpRecover,fk.DamageInflicted},
  can_trigger = function(self, event, target, player, data)
    if event == fk.PreHpRecover then
      return  player == target and target:getMark("@@joy__jieyuerecover-turn") > 0
    elseif event == fk.DamageInflicted then
      return player == target and target:getMark("@@joy__jieyuedamage-turn") > 0
    end
  end,
  on_cost = Util.TrueFunc,
  on_use = function(self, event, target, player, data)
    if event == fk.PreHpRecover then
      return true
    elseif event == fk.DamageInflicted then
      data.damage = data.damage + 1
    end
  end,
}
local jieyue_prohibit = fk.CreateProhibitSkill{
  name = "#joy__jieyue_prohibit",
  prohibit_use = function(self, player, card)
    if player:getMark("@@joy__jieyuecard-turn") > 0 then
      local cardlist = Card:getIdList(card)
      return #cardlist > 0 and table.every(cardlist, function(id)
        return table.contains(player:getCardIds(Player.Hand), id)
      end)
    end
  end,
  prohibit_response = function(self, player, card)
    if player:getMark("@@joy__jieyuecard-turn") > 0 then
      local cardlist = Card:getIdList(card)
      return #cardlist > 0 and table.every(cardlist, function(id)
        return table.contains(player:getCardIds(Player.Hand), id)
      end)
    end
  end,
}
local xiayuan = fk.CreateTriggerSkill{
  name = "joy_mou__xiayuan",
  anim_type = "support",
  events = {fk.EnterDying},
  can_trigger = function(self, event, target, player, data)
      return player:hasSkill(self) and target ~= player and not player:isNude() and
        player:usedSkillTimes(self.name, Player.HistoryRound) == 0
  end,
  on_cost = function(self, event, target, player, data)
      local cards = player.room:askForDiscard(player, 1, 2, true, self.name, true, ".", "#joy_mou__xiayuan-invoke::"..target.id)
      if #cards > 0 then
        self.cost_data = #cards
        return true
      end
  end,
  on_use = function(self, event, target, player, data)
    local n = self.cost_data
    if target:isWounded() then
      player.room:recover({
        who = target,
        num = math.min(target.maxHp - target.hp,n),
        recoverBy = player,
        skillName = self.name
        })
    end
  end,
}
jieyue:addRelatedSkill(jieyue_trigger)
jieyue:addRelatedSkill(jieyue_prohibit)
Fk:addSkill(jieyue_active)
mouyujin:addSkill(jieyue)
mouyujin:addSkill(xiayuan)
Fk:loadTranslationTable{
  ["joy_mou__yujin"] = "谋于禁",
  ["joy_mou__jieyue"] = "节钺",
  [":joy_mou__jieyue"] = "准备阶段，你可以令一名其他角色摸一张牌，然后令其执行一次“军令”。"..
  "<br>若其执行，你摸一张牌；"..
  "<br>若其不执行，你摸三张牌，然后其本回合受到的伤害+1."..
  "<font color='grey'><br><b>军令一：</b>对你指定的一名角色造成1点伤害。<br><b>军令二：</b>随机弃置一张手牌和一张装备牌。<br><b>军令三：</b>本回合不能恢复体力。<br><b>军令四：</b>本回合不能使用或打出手牌且所有非锁定技失效。",
  ["joy_mou__xiayuan"] = "狭援",
  [":joy_mou__xiayuan"] = "每轮限一次，其他角色濒死时，你可以弃置至多两张牌，令其回复等同于弃置牌数的体力。",

  ["joy_mou__jieyue_active"] = "军令",
  ["#joy_mou__jieyue-invoke"] = "节钺：你可以令一名其他角色选择是否执行军令",
  ["#joy__jieyue1-choose"] = "军令一：选择你想让执行军令角色造成伤害的目标。",
  ["joy__jieyue1"] = "军令一：对你指定的一名角色造成1点伤害。",
  ["joy__jieyue2"] = "军令二：随机弃置一张手牌和一张装备牌。",
  ["joy__jieyue3"] = "军令三：本回合不能恢复体力。",
  ["joy__jieyue4"] = "军令四：本回合不能使用或打出手牌且所有非锁定技失效。",

  ["#joy__junling1"] = "是否执行军令：对 %dest 造成1点伤害",
  ["#joy__junling2"] = "是否执行军令：随机弃置一张手牌和装备牌 ",
  ["#joy__junling3"] = "是否执行军令：本回合不能恢复体力",
  ["#joy__junling4"] = "是否执行军令：本回合不能使用或打出手牌且所有非锁定技失效 ",
  ["#joy_mou__xiayuan-invoke"] = "狭援：你可以弃置至多两张牌，令 %dest 回复等同于弃置数的体力",

  ["#joy_mou__jieyue_trigger"] = "节钺",
  ["#joy__jieyue_prohibit"] = "节钺",
  ["@@joy__jieyuerecover-turn"] = "军令三",
  ["@@joy__jieyuecard-turn"] = "军令四",
  ["@@joy__jieyuedamage-turn"] = "受伤+1",



}


local mou__xuhuang = General:new(extension, "joy_mou__xuhuang", "wei", 4, 4)
local mou__duanliang = fk.CreateActiveSkill{
  name = "joy_mou__duanliang",
  anim_type = "control",
  mute = true,
  can_use = function(self, player)
    return player:usedSkillTimes(self.name, Player.HistoryPhase) < 2
  end,
  card_num = 0,
  card_filter = function() return false end,
  target_num = 1,
  target_filter = function(self, to_select, selected)
    return #selected == 0 and to_select ~= Self.id
  end,
  on_use = function(self, room, effect)
    local player = room:getPlayerById(effect.from)
    local to = room:getPlayerById(effect.tos[1])
    local id1
    if not player.dead then
     id1 = player:drawCards(1,self.name)
    end
    room:notifySkillInvoked(player, self.name)
    player:broadcastSkillInvoke(self.name, 1)
    local choices = U.doStrategy(room, player, to, {"mou__duanliang-weicheng","mou__duanliang-jinjun"}, {"mou__duanliang-tuji","mou__duanliang-shoucheng"}, self.name, 1)
    if choices[1] == "mou__duanliang-weicheng" and choices[2] ~= "mou__duanliang-tuji" then
      player:broadcastSkillInvoke(self.name, 2)
      local use
      if #id1 > 0 and table.every(id1, function(id) return table.contains(player:getCardIds("h"), id) end) then
        local card = Fk:cloneCard("supply_shortage")
        card.skillName = self.name
        card:addSubcard(id1[1])
        if U.canUseCardTo(room, player, to, card, false) then
          room:useVirtualCard("supply_shortage", {id1[1]}, player, to, self.name, true)
          use = true
        end
      end
      if not use and not to:isNude() then
        local id = room:askForCardChosen(player, to, "he", self.name)
        room:obtainCard(player, id, false, fk.ReasonPrey)
      end
    elseif choices[1] == "mou__duanliang-jinjun" and choices[2] ~= "mou__duanliang-shoucheng" then
      player:broadcastSkillInvoke(self.name, 3)
      room:useVirtualCard("duel", nil, player, to, self.name)
    else
      player:broadcastSkillInvoke(self.name, 4)
    end
  end,
}
mou__xuhuang:addSkill(mou__duanliang)
local mou__shipo = fk.CreateTriggerSkill{
  name = "joy_mou__shipo",
  anim_type = "control",
  events = {fk.EventPhaseStart},
  can_trigger = function(self, event, target, player, data)
    if target == player and player:hasSkill(self) and player.phase == Player.Finish then
      return table.find(player.room:getOtherPlayers(player), function (p) return p.hp < player.hp or p:hasDelayedTrick("supply_shortage") end)
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local targets1 = table.filter(player.room.alive_players, function (p) return p.hp < player.hp end)
    local targets2 = table.filter(player.room:getOtherPlayers(player), function (p) return p:hasDelayedTrick("supply_shortage") end)
    local choices = {}
    if #targets1 > 0 then table.insert(choices, "mou__shipo_choice1") end
    if #targets2 > 0 then table.insert(choices, "mou__shipo_choice2") end
    local choice = room:askForChoice(player, choices, self.name, "#mou__shipo-choose")
    local targets = {}
    if choice == "mou__shipo_choice2" then
      targets = targets2
    else
      local tos = room:askForChoosePlayers(player, table.map(targets1, Util.IdMapper), 1, 1, "#mou__shipo-choose", self.name, false)
      targets = {room:getPlayerById(tos[1])}
    end
    for _, to in ipairs(targets) do
      if player.dead then break end
      local card = room:askForCard(to, 1, 1, false, self.name, true, ".", "#mou__shipo-give::"..player.id)
      if #card > 0 then
        local get = card[1]
        room:obtainCard(player, get, false, fk.ReasonGive)
        if room:getCardArea(get) == Card.PlayerHand and room:getCardOwner(get) == player then
          local tos = room:askForChoosePlayers(player, table.map(room:getOtherPlayers(player), Util.IdMapper), 1, 1, "#mou__shipo-present:::"..Fk:getCardById(get):toLogString(), self.name, true)
          if #tos > 0 then
            room:obtainCard(tos[1], get, false, fk.ReasonGive)
          end
        end
      else
        room:damage { from = player, to = to, damage = 1, skillName = self.name }
      end
    end
  end,
}
mou__xuhuang:addSkill(mou__shipo)
Fk:loadTranslationTable{
  ["joy_mou__xuhuang"] = "谋徐晃",
  ["joy_mou__duanliang"] = "断粮",
  [":joy_mou__duanliang"] = "出牌阶段限两次，你可以摸一张牌并与一名其他角色进行一次“谋弈”：<br>围城断粮，你将此牌当做无距离限制的【兵粮寸断】对其使用，若无法使用改为你获得其一张牌；<br>擂鼓进军，你视为对其使用一张【决斗】。",

  ["joy_mou__shipo"] = "势迫",
  [":joy_mou__shipo"] = "结束阶段，你可以令一名体力值小于你的角色或所有判定区里有【兵粮寸断】的其他角色选择一项：1.交给你一张手牌，且你可以将此牌交给一名其他角色；2.受到1点伤害。",

  ["$joy_mou__duanliang1"] = " ",
  ["$joy_mou__duanliang2"] = " ",
  ["$joy_mou__duanliang3"] = " ",
  ["$joy_mou__duanliang4"] = " ",
  ["$joy_mou__shipo1"] = " ",
  ["$joy_mou__shipo2"] = " ",
  ["~joy_mou__xuhuang"] = " ",
}

local joymou__simayi = General(extension, "joy_mou__simayi", "wei", 3)
local pingliao = fk.CreateTriggerSkill{
  name = "joy__pingliao",
  anim_type = "control",
  events = {fk.CardUsing},
  frequency = Skill.Compulsory,
  can_trigger = function(self, event, target, player, data)
    return player == target and player:hasSkill(self) and data.card.trueName == "slash"
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local targets = table.filter(room:getAlivePlayers(), function (p)
      return player:inMyAttackRange(p)
    end)
    room:doIndicate(player.id, table.map(targets, Util.IdMapper))
    local tos = TargetGroup:getRealTargets(data.tos)
    local drawcard = false
    local targets2 = {}
    for _, p in ipairs(targets) do
      local card = room:askForResponse(p, self.name, ".|.|heart,diamond|.|.|basic", "#joy__pingliao-ask:" .. player.id, true)
      if card then
        room:responseCard{
          from = p.id,
          card = card
        }
        if not table.contains(tos, p.id) then
          drawcard = true
        end
      elseif table.contains(tos, p.id) then
        table.insert(targets2, p)
      end
    end
    for _, p in ipairs(targets2) do
      room:setPlayerMark(p, "@@joy__pingliao-turn", 1)
    end
    if player.dead then return false end
    if drawcard then
      player:drawCards(2, self.name)
      room:addPlayerMark(player, MarkEnum.SlashResidue .. "-phase")
    end
  end,

  refresh_events = {fk.PreCardUse},
  can_refresh = function (self, event, target, player, data)
    return player == target and player:hasSkill(self) and data.card.trueName == "slash"
  end,
  on_refresh = function (self, event, target, player, data)
    data.noIndicate = true
  end,
}
local pingliao_prohibit = fk.CreateProhibitSkill{
  name = "#joy__pingliao_prohibit",
  prohibit_use = function(self, player, card)
    if player:getMark("@@joy__pingliao-turn") > 0 then
      local subcards = card:isVirtual() and card.subcards or {card.id}
      return #subcards > 0 and table.every(subcards, function(id)
        return table.contains(player:getCardIds(Player.Hand), id)
      end)
    end
  end,
  prohibit_response = function(self, player, card)
    if player:getMark("@@joy__pingliao-turn") > 0 then
      local subcards = card:isVirtual() and card.subcards or {card.id}
      return #subcards > 0 and table.every(subcards, function(id)
        return table.contains(player:getCardIds(Player.Hand), id)
      end)
    end
  end,
}
local quanmou = fk.CreateActiveSkill{
  name = "joy__quanmou",
  anim_type = "switch",
  switch_skill_name = "joy__quanmou",
  card_num = 0,
  target_num = 1,
  prompt = function ()
    return Self:getSwitchSkillState("joy__quanmou", false) == fk.SwitchYang and "#joy__quanmou-Yang" or "#joy__quanmou-Yin"
  end,
  can_use = Util.TrueFunc,
  card_filter = Util.FalseFunc,
  target_filter = function(self, to_select, selected, selected_cards)
    if #selected == 0 and not table.contains(Self:getTableMark( "joy__quanmou_targets-phase"), to_select) then
      local target = Fk:currentRoom():getPlayerById(to_select)
      return not target:isNude() and Self:inMyAttackRange(target)
    end
  end,
  on_use = function(self, room, effect)
    local player = room:getPlayerById(effect.from)
    local target = room:getPlayerById(effect.tos[1])
    local mark = player:getTableMark( "joy__quanmou_targets-phase")
    table.insert(mark, target.id)
    room:setPlayerMark(player, "joy__quanmou_targets-phase", mark)

    local isYang = player:getSwitchSkillState(self.name, true) == fk.SwitchYang
    local from_name = "joy_mou__simayi"
    local to_name = "joy_mou__simayi"
    if isYang then
      to_name = "joy_mou2__simayi"
    else
      from_name = "joy_mou2__simayi"
    end
    if player.general == from_name then
      player.general = to_name
      room:broadcastProperty(player, "general")
    end
    if player.deputyGeneral == from_name then
      player.deputyGeneral = to_name
      room:broadcastProperty(player, "deputyGeneral")
    end

    local card = room:askForCard(target, 1, 1, true, self.name, false, ".", "#joy__quanmou-give::"..player.id)
    room:obtainCard(player.id, card[1], false, fk.ReasonGive, target.id)
    if player.dead or target.dead then return false end
    room:setPlayerMark(target, "@joy__quanmou-phase", isYang and "yang" or "yin")
    local mark_name = "joy__quanmou_" .. (isYang and "yang" or "yin") .. "-phase"
    mark = player:getTableMark( mark_name)
    table.insert(mark, target.id)
    room:setPlayerMark(player, mark_name, mark)
  end,
}
local function setTYMouSwitchSkillState(player, generalName, skillName, isYang)
  if isYang == nil then
    isYang = player:getSwitchSkillState(skillName, true) == fk.SwitchYang
  else
    local switch_state = isYang and fk.SwitchYin or fk.SwitchYang
    if player:getSwitchSkillState(skillName, true) == switch_state then
      player.room:setPlayerMark(player, MarkEnum.SwithSkillPreName .. skillName, switch_state)
      player:setSkillUseHistory(skillName, 0, Player.HistoryGame)
    end
  end

  if Fk.generals["joy_mou2__" .. generalName] == nil then return end

  local from_name = "joy_mou__" .. generalName
  local to_name = "joy_mou__" .. generalName
  if isYang then
    to_name = "joy_mou2__" .. generalName
  else
    from_name = "jou_mou2__" .. generalName
  end
  if player.general == from_name then
    player.general = to_name
    player.room:broadcastProperty(player, "general")
  end
  if player.deputyGeneral == from_name then
    player.deputyGeneral = to_name
    player.room:broadcastProperty(player, "deputyGeneral")
  end
end

Fk:loadTranslationTable{
  ["joy_mou_switch"] = "%arg · %arg2",
  ["#joy_mou_switch-transer"] = "请选择 %arg 的阴阳状态",
}
local quanmou_switch = fk.CreateTriggerSkill{
  name = "#joy__quanmou_switch",
  events = {fk.GameStart},
  mute = true,
  can_trigger = function(self, event, target, player, data)
    return player:hasSkill(quanmou)
  end,
  on_cost = Util.TrueFunc,
  on_use = function(self, event, target, player, data)
    setTYMouSwitchSkillState(player, "simayi", "joy__quanmou",
    player.room:askForChoice(player, { "joy_mou_switch:::joy__quanmou:yang", "joy_mou_switch:::joy__quanmou:yin" },
    "joy__quanmou", "#joy_mou_switch-transer:::joy__quanmou") == "joy_mou_switch:::joy__quanmou:yin")
  end,
}
local quanmou_delay = fk.CreateTriggerSkill{
  name = "#joy__quanmou_delay",
  events = {fk.DamageCaused, fk.Damage},
  mute = true,
  can_trigger = function(self, event, target, player, data)
    local isYang = player:getSwitchSkillState(self.name, false) == fk.SwitchYang
    if event == fk.GameStart and ((isYang and player.general == "joy_mou2__simayi") or (not isYang and player.general == "joy_mou__simayi")) then return true end
    if player.dead or player.phase ~= Player.Play or player ~= target then return false end
    if event == fk.DamageCaused then
      return table.contains(player:getTableMark( "joy__quanmou_yang-phase"), data.to.id)
    elseif event == fk.Damage then
      return table.contains(player:getTableMark( "joy__quanmou_yin-phase"), data.to.id)
    end
  end,
  on_cost = Util.TrueFunc,
  on_use = function(self, event, target, player, data)
    local room = player.room
    if event == fk.GameStart then
      local isYang = player:getSwitchSkillState(self.name, false) == fk.SwitchYang
      local from_name = "joy_mou2__simayi"
      local to_name = "joy_mou2__simayi"
      if isYang then
        to_name = "joy_mou__simayi"
      else
        from_name = "joy_mou__simayi"
      end
      if player.general == from_name then
        player:broadcastSkillInvoke("joy__quanmou")
        room:notifySkillInvoked(player, "joy__quanmou")
        player.general = to_name
        room:broadcastProperty(player, "general")
      end
      if player.deputyGeneral == from_name then
        player:broadcastSkillInvoke("joy__quanmou")
        room:notifySkillInvoked(player, "joy__quanmou")
        player.deputyGeneral = to_name
        room:broadcastProperty(player, "deputyGeneral")
    end
    else
    room:doIndicate(player.id, {data.to.id})
    room:setPlayerMark(data.to, "@joy__quanmou-phase", 0)
    if event == fk.DamageCaused then
      local mark = player:getTableMark( "joy__quanmou_yang-phase")
      table.removeOne(mark, data.to.id)
      room:setPlayerMark(player, "joy__quanmou_yang-phase", mark)
      room:notifySkillInvoked(player, "joy__quanmou", "defensive")
      if player:getSwitchSkillState("joy__quanmou", false) == fk.SwitchYang then
        player:broadcastSkillInvoke("joy__quanmou")
      end
      return true
    elseif event == fk.Damage then
      local mark = player:getTableMark( "joy__quanmou_yin-phase")
      table.removeOne(mark, data.to.id)
      room:setPlayerMark(player, "joy__quanmou_yin-phase", mark)
      room:notifySkillInvoked(player, "joy__quanmou", "offensive")
      if player:getSwitchSkillState("joy__quanmou", false) == fk.SwitchYin then
        player:broadcastSkillInvoke("joy__quanmou")
      end
      local targets = table.filter(room.alive_players, function (p)
        return p ~= player and p ~= data.to
      end)
      if #targets == 0 then return false end
      targets = room:askForChoosePlayers(player, table.map(targets, Util.IdMapper), 1, 3, "#joy__quanmou-damage", "joy__quanmou")
      if #targets == 0 then return false end
      room:sortPlayersByAction(targets)
      for _, id in ipairs(targets) do
        local p = room:getPlayerById(id)
        if not p.dead then
          room:damage{
            from = player,
            to = p,
            damage = 1,
            skillName = "joy__quanmou",
          }
        end
      end
    end
    end
  end,
}
quanmou:addRelatedSkill(quanmou_switch)
pingliao:addRelatedSkill(pingliao_prohibit)
quanmou:addRelatedSkill(quanmou_delay)
joymou__simayi:addSkill(pingliao)
joymou__simayi:addSkill(quanmou)

local joymou2__simayi = General(extension, "joy_mou2__simayi", "wei", 3)
joymou2__simayi.hidden = true
joymou2__simayi:addSkill("joy__pingliao")
joymou2__simayi:addSkill("joy__quanmou")

Fk:loadTranslationTable{
  ["joy_mou__simayi"] = "谋司马懿",
  ["#joy_mou__simayi"] = "韬谋韫势",

  ["joy__pingliao"] = "平辽",
  [":joy__pingliao"] = "锁定技，<font color='red'>当你使用【杀】指定目标时，不公开指定的目标。</font>"..
  "你攻击范围内的其他角色依次选择是否打出一张红色基本牌。"..
  "若此【杀】的目标未打出基本牌，其本回合无法使用或打出手牌；若有至少一名非目标打出基本牌，你摸两张牌且此阶段使用【杀】的次数上限+1。",
  ["joy__quanmou"] = "权谋",
  [":joy__quanmou"] = "转换技，出牌阶段每名角色限一次，你可以令攻击范围内的一名其他角色交给你一张牌，"..
  "阳：防止你此阶段下次对其造成的伤害；阴：你此阶段下次对其造成伤害后，可以对至多三名该角色外的其他角色各造成1点伤害。",

  ["#joy__pingliao-ask"] = "平辽：%src 使用了一张【杀】，你可以打出一张红色基本牌",
  ["@@joy__pingliao-turn"] = "平辽",
  ["#joy__quanmou-Yang"] = "发动 权谋（阳），选择攻击范围内的一名角色",
  ["#joy__quanmou-Yin"] = "发动 权谋（阴），选择攻击范围内的一名角色",
  ["#joy__quanmou-give"] = "权谋：选择一张牌交给 %dest ",
  ["@joy__quanmou-phase"] = "权谋",
  ["#joy__quanmou_delay"] = "权谋",
  ["#joy__quanmou-damage"] = "权谋：你可以选择1-3名角色，对这些角色各造成1点伤害",

  --阳形态
  ["$joy__pingliao1"] = "烽烟起大荒，戎军远役，问不臣者谁？",
  ["$joy__pingliao2"] = "挥斥千军之贲，长驱万里之远。",
  ["$joy__quanmou1"] = "洛水为誓，皇天为证，吾意不在刀兵。",
  ["$joy__quanmou2"] = "以谋代战，攻形不以力，攻心不以勇。",
  ["~joy_mou__simayi"] = "以权谋而立者，必失大义于千秋……",

  --阴形态
  ["joy_mou2__simayi"] = "谋司马懿",
  ["#joy_mou2__simayi"] = "韬谋韫势",

  ["$joy__pingliao_joy_mou2__simayi1"] = "率土之滨皆为王臣，辽土亦居普天之下。",
  ["$joy__pingliao_joy_mou2__simayi2"] = "青云远上，寒锋试刃，北雁当寄红翎。",
  ["$joy__quanmou_joy_mou2__simayi1"] = "鸿门之宴虽歇，会稽之胆尚悬，孤岂姬、项之辈？",
  ["$joy__quanmou_joy_mou2__simayi2"] = "昔藏青锋于沧海，今潮落，可现兵！",
  ["~joy_mou2__simayi"] = "人立中流，非已力可向，实大势所迫……",
}


local sunshangxiang = General(extension, "joy_mou__sunshangxiang", "wu", 3, 3, General.Female)
local jieyin = fk.CreateActiveSkill{
  name = "joy_mou__jieyin",
  anim_type = "support",
  prompt = "结姻：选择一名有“姻”的其他角色。",
  interaction = function(self)
    return UI.ComboBox {choices = {"交给一张牌","置入装备牌"}}
  end,
  card_num = 1,
  target_num = 1,
  can_use = function(self, player)
    return player:usedSkillTimes(self.name, Player.HistoryPhase) == 0
  end,
  card_filter = function(self, to_select, selected)
    local ch = self.interaction.data
    if ch == "置入装备牌" then
      return #selected == 0 and Fk:getCardById(to_select).type == Card.TypeEquip
    else
      return #selected == 0 and Fk:currentRoom():getCardArea(to_select) == Player.Hand
    end
  end,
  target_filter = function(self, to_select, selected, selected_cards)
    if #selected == 0 and to_select ~= Self.id and #selected_cards == 1 then
      local target = Fk:currentRoom():getPlayerById(to_select)
      if target and target:getMark("@@joy_mou_yan") > 0 then
        local ch = self.interaction.data
        if ch == "置入装备牌" then
          local card = Fk:getCardById(selected_cards[1])
          return #target:getAvailableEquipSlots(card.sub_type) > 0
        else
          return true
        end
      end
    end
  end,
  on_use = function(self, room, effect)
    local player = room:getPlayerById(effect.from)
    local target = room:getPlayerById(effect.tos[1])
    local ch = self.interaction.data
    if ch == "置入装备牌" then
      room:moveCards({
        ids = effect.cards,
        from = effect.from,
        to = effect.tos[1],
        toArea = Card.PlayerEquip,
        skillName = self.name,
        moveReason = fk.ReasonPut,
      })
    else
      room:obtainCard(target, effect.cards[1], false, fk.ReasonGive)
    end
    if player.dead then return end
    if player:isWounded() then
      room:recover({
        who = player,
        num = 1,
        recoverBy = player,
        skillName = self.name
      })
    end
    if not player.dead then
      player:drawCards(1,self.name)
    end
  end,
}
local jieyin_trigger = fk.CreateTriggerSkill{
  name = "#joy_mou__jieyin_trigger",
  events = {fk.GameStart, fk.Death},
  mute = true,
  can_trigger = function(self, event, target, player, data)
    if event == fk.GameStart then
      return player:hasSkill(self) and #player.room.alive_players > 0
    elseif event == fk.Death then
      return player:hasSkill(self) and target:getMark("@@joy_mou_yan") > 0 and #target:getCardIds("hej") > 0
    end
  end,
  on_cost =  function(self, event, target, player, data)
    local room = player.room
    if event == fk.GameStart then
      local targets = {}
      for _, p in ipairs(room:getOtherPlayers(player)) do
        if p:getMark("@@joy_mou_yan") == 0 then
          table.insertIfNeed(targets,p.id)
        end
      end
      if #targets <= 0 then return false end
      local tos = room:askForChoosePlayers(player, targets, 1, 1, "结姻：你可以选择一名其他角色，令其与你各获得“姻”标记，然后其获得技能〖结姻〗。", self.name,true)
      if #tos > 0 then
        self.cost_data = tos[1]
        return true
      end
    else
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    if event == fk.GameStart then
      room:notifySkillInvoked(player, self.name,"special")
      player:broadcastSkillInvoke(self.name, 1)
      local to = room:getPlayerById(self.cost_data)
      room:setPlayerMark(to, "@@joy_mou_yan", 1)
      room:setPlayerMark(player, "@@joy_mou_yan", 1)
      room:handleAddLoseSkills(to,"joy_mou__jieyin",nil,true)
      room:changeKingdom(player,to.kingdom, true)
    elseif event == fk.Death then
      room:notifySkillInvoked(player, self.name,"drawcard")
      local cards = target:getCardIds("hej")
      if #cards > 0 then
        local dummy = Fk:cloneCard'slash'
        dummy:addSubcards(cards)
        room:obtainCard(player.id, dummy, false, fk.ReasonPrey)
      end
    end
  end,
}
local fanxiang = fk.CreateActiveSkill{
  name = "joy_mou__fanxiang",
  anim_type = "offensive",
  card_num = 0,
  target_num = 0,
  prompt = "返乡：获得其他有“姻”的角色所有装备区的牌，然后移除全场“姻”与技能〖结姻〗。",
  frequency = Skill.Limited,
  can_use = function(self, player)
    return player:usedSkillTimes(self.name, Player.HistoryGame) == 0
  end,
  card_filter = Util.FalseFunc,
  on_use = function(self, room, effect)
    local player = room:getPlayerById(effect.from)
    local cards = {}
    for _, p in ipairs(room:getOtherPlayers(player)) do
      if p:getMark("@@joy_mou_yan") > 0 and #p:getCardIds("e") > 0 then
        table.insertTableIfNeed(cards,p:getCardIds("e"))
      end
    end
    if #cards > 0 then
      local dummy = Fk:cloneCard'slash'
      dummy:addSubcards(cards)
      room:obtainCard(player.id, dummy, false, fk.ReasonPrey)
    end
    for _, p in ipairs(room.alive_players) do
      room:setPlayerMark(p,"@@joy_mou_yan",0)
      room:handleAddLoseSkills(p,"-joy_mou__jieyin")
    end
    if player.dead then return end
    room:handleAddLoseSkills(player,"joy__wujian")
    room:changeKingdom(player,"wu", true)
  end,
}
local xiaoji = fk.CreateTriggerSkill{
  name = "joy_mou__xiaoji",
  anim_type = "drawcard",
  events = {fk.AfterCardsMove},
  can_trigger = function(self, event, target, player, data)
    if not player:hasSkill(self) then return end
    for _, move in ipairs(data) do
      if move.from == player.id then
        for _, info in ipairs(move.moveInfo) do
          if info.fromArea == Card.PlayerEquip then
            return true
          end
        end
      end
    end
  end,
  on_trigger = function(self, event, target, player, data)
    local i = 0
    for _, move in ipairs(data) do
      if move.from == player.id then
        for _, info in ipairs(move.moveInfo) do
          if info.fromArea == Card.PlayerEquip then
            i = i + 1
          end
        end
      end
    end
    self.cancel_cost = false
    for _ = 1, i do
      if self.cancel_cost or not player:hasSkill(self) then break end
      self:doCost(event, target, player, data)
    end
  end,
  on_cost = function(self, event, target, player, data)
    if player.room:askForSkillInvoke(player, self.name) then
      return true
    end
    self.cancel_cost = true
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    room:drawCards(player, 2, self.name)
    if player.dead then return false end
    local targets = table.map(table.filter(room.alive_players, function (p)
      return #p:getCardIds("ej") > 0
    end), Util.IdMapper)
    if #targets == 0 then return false end
    local tos = room:askForChoosePlayers(player, targets, 1, 1, "#joy_mou__xiaoji-discard", self.name, true)
    if #tos == 0 then return false end
    local to = room:getPlayerById(tos[1])
    local card = room:askForCardChosen(player, to, "ej", self.name)
    room:throwCard({card}, self.name, to, player)
  end,
}
jieyin:addRelatedSkill(jieyin_trigger)
sunshangxiang:addSkill(xiaoji)
sunshangxiang:addSkill(jieyin)
sunshangxiang:addSkill(fanxiang)
sunshangxiang:addRelatedSkill("joy__wujian")

Fk:loadTranslationTable{
  ["joy_mou__sunshangxiang"] = "谋孙尚香",
  ["#joy_mou__sunshangxiang"] = "骄豪明俏",
  
  ["joy_mou__jieyin"] = "结姻",
  ["#joy_mou__jieyin_trigger"] = "结姻",
  [":joy_mou__jieyin"] = "游戏开始时，你可选择一名其他角色，令你与其获得“姻”标记，然后其获得技能〖结姻〗,你将势力变更至与其相同；有“姻”的角色死亡时，你获得其区域内所有牌。"..
  "<br>出牌阶段限一次，你可以交给一名有“姻”的角色一张手牌或将一张装备牌置入其装备区，然后你回复一点体力并摸一张牌。",
  ["@@joy_mou_yan"] = "姻",

  ["joy_mou__fanxiang"] = "返乡",
  [":joy_mou__fanxiang"] = "限定技，出牌阶段，你可以获得全场有“姻”的其他角色所有装备区的牌，并令场上所有角色失去“姻”和〖结姻〗,然后你获得技能〖剑舞〗并变更势力为吴。",
  ["joy_mou__xiaoji"] = "枭姬",
  [":joy_mou__xiaoji"] = "吴势力技，当你失去装备区里的一张牌后，你摸两张牌，然后你可以弃置场上的一张牌。",

  ["#joy_mou__xiaoji-discard"] = "枭姬：你可以选择一名角色，弃置其装备区或判定区里的一张牌",

}

local zhouyu = General(extension, "joy_mou__zhouyu", "wu", 4)
zhouyu:addSkill("ronghuo")
zhouyu:addSkill("yingmou")

Fk:loadTranslationTable{
  ["joy_mou__zhouyu"] = "谋周瑜",
  ["#joy_mou__zhouyu"] = "炽谋英隽",
}

local jiangwei = General(extension, "joy_mou__jiangwei", "shu", 4)
jiangwei:addSkill("zhuri")
jiangwei:addSkill("ranji")
jiangwei:addRelatedSkill("kunfenEx")
jiangwei:addRelatedSkill("ol_ex__zhaxiang")

Fk:loadTranslationTable{
  ["joy_mou__jiangwei"] = "谋姜维",
  ["#joy_mou__jiangwei"] = "炎志灼心",
}

local xiahoushi = General(extension, "joy_mou__xiahoushi", "shu", 3, 3, General.Female)

local yanyu = fk.CreateTriggerSkill{
  name = "joy_mou__yanyu",
  anim_type = "support",
  events = {fk.EventPhaseStart},
  can_trigger = function(self, event, target, player, data)
    return player:hasSkill(self) and target.phase == Player.Play and not player:isNude()
  end,
  on_cost = function(self, event, target, player, data)
    local card = player.room:askForDiscard(player, 1, 1, true, self.name, true, ".", "#joy_mou__yanyu-cost", true)
    if #card > 0 then
      self.cost_data = card
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local card_type = Fk:getCardById(self.cost_data[1]):getTypeString()
    room:throwCard(self.cost_data, self.name, player, player)
    local x = 2 - player:usedSkillTimes("#joy_mou__yanyu_delay", Player.HistoryTurn)
    if not player.dead and x > 0 then
      room:setPlayerMark(player, "@joy_mou__yanyu-phase", {card_type, x})
    end
  end,
}
local yanyu_active = fk.CreateActiveSkill{
  name = "joy_mou__yanyu_active",
  expand_pile = function(self)
    return Self:getTableMark( "joy_mou__yanyu_cards")
  end,
  card_num = 1,
  target_num = 1,
  card_filter = function(self, to_select, selected, targets)
    return #selected == 0 and table.contains(Self:getTableMark( "joy_mou__yanyu_cards"), to_select)
  end,
  target_filter = function(self, to_select, selected, selected_cards)
    return #selected == 0
  end,
}
Fk:addSkill(yanyu_active)
local yanyu_delay = fk.CreateTriggerSkill{
  name = "#joy_mou__yanyu_delay",
  anim_type = "support",
  events = {fk.AfterCardsMove},
  can_trigger = function(self, event, target, player, data)
    if player.dead or player:usedSkillTimes(self.name, Player.HistoryTurn) > 1 then return false end
    local mark = player:getMark("@joy_mou__yanyu-phase")
    if type(mark) == "table" and #mark == 2 then
      local type_name = mark[1]
      local ids = {}
      local id = -1
      local room = player.room
      for _, move in ipairs(data) do
        if move.toArea == Card.DiscardPile then
          for _, info in ipairs(move.moveInfo) do
            id = info.cardId
            if Fk:getCardById(id):getTypeString() == type_name and room:getCardArea(id) == Card.DiscardPile then
              table.insertIfNeed(ids, id)
            end
          end
        end
      end
      ids = U.moveCardsHoldingAreaCheck(room, ids)
      if #ids > 0 then
        self.cost_data = ids
        return true
      end
    end
  end,
  on_trigger = function(self, event, target, player, data)
    local room = player.room
    local ids = table.simpleClone(self.cost_data)
    while true do
      self.cancel_cost = false
      self:doCost(event, nil, player, ids)
      if self.cancel_cost then
        self.cancel_cost = false
        break
      end
      if player.dead or player:usedSkillTimes(self.name, Player.HistoryTurn) > 1 then break end
      ids = U.moveCardsHoldingAreaCheck(room, ids)
      if #ids == 0 then break end
    end
  end,
  on_cost = function(self, event, target, player, data)
    local room = player.room
    room:setPlayerMark(player, "joy_mou__yanyu_cards", data)
    local _, ret = room:askForUseActiveSkill(player, "joy_mou__yanyu_active", "#yanyu-choose", true, nil, true)
    room:setPlayerMark(player, "joy_mou__yanyu_cards", 0)
    if ret then
      self.cost_data = {ret.targets[1], ret.cards[1]}
      return true
    end
    self.cancel_cost = true
  end,
  on_use = function(self, event, target, player, data)
    player:broadcastSkillInvoke("joy_mou__yanyu")
    local mark = player:getMark("@joy_mou__yanyu-phase")
    if type(mark) == "table" or #mark == 2 then
      local x = 2 - player:usedSkillTimes(self.name, Player.HistoryTurn)
      player.room:setPlayerMark(player, "@joy_mou__yanyu-phase", x > 0 and {mark[1], x} or 0)
    end
    player.room:obtainCard(self.cost_data[1], self.cost_data[2], true, fk.ReasonGive)
  end,
}
xiahoushi:addSkill("mou__qiaoshi")
yanyu:addRelatedSkill(yanyu_delay)
xiahoushi:addSkill(yanyu)

Fk:loadTranslationTable{
  ["joy_mou__xiahoushi"] = "谋夏侯氏",
  ["#joy_mou__xiahoushi"] = "燕语呢喃",
  ["joy_mou__yanyu"] = "燕语",
  [":joy_mou__yanyu"] = "任意一名角色的出牌阶段开始时，你可以弃置一张牌，若如此做，则本回合的出牌阶段，当有与你弃置牌类别相同的其他牌进入弃牌堆时，"..
  "你可令任意一名角色获得此牌。每回合以此法获得的牌不能超过两张。",

  ["@joy_mou__yanyu-phase"] = "燕语",
  ["#joy_mou__yanyu_delay"] = "燕语",
  ["#joy_mou__yanyu-cost"] = "燕语：你可以弃置一张牌，然后此出牌阶段限两次，可令任意角色获得相同类别进入弃牌堆的牌",
  ["joy_mou__yanyu_active"] = "燕语",
  ["#joy_mou__yanyu-choose"] = "燕语：令一名角色获得弃置的牌",
}

---@param pattern string
---@param num? number
---@return integer[] @ id列表 可能空
local getCards = function(self,pattern, num)
  num = num or 1
  local pileToSearch = {}
  for _, t in ipairs({self.void,self.draw_pile,self.discard_pile}) do
    table.insertTable(pileToSearch,t)
  end
  if #pileToSearch == 0 then
    return {}
  end

  local cardPack = {}
  if num < 3 then
    for i = 1, num do
      local randomIndex = math.random(1, #pileToSearch)
      local curIndex = randomIndex
      repeat
        local curCardId = pileToSearch[curIndex]
        if Fk:getCardById(curCardId):matchPattern(pattern) and not table.contains(cardPack, curCardId) then
          table.insert(cardPack, pileToSearch[curIndex])
          break
        end

        curIndex = curIndex + 1
        if curIndex > #pileToSearch then
          curIndex = 1
        end
      until curIndex == randomIndex

      if #cardPack == 0 then
        break
      end
    end
  else
    local matchedIds = {}
    for _, id in ipairs(pileToSearch) do
      if Fk:getCardById(id):matchPattern(pattern) then
        table.insert(matchedIds, id)
      end
    end

    local loopTimes = math.min(num, #matchedIds)
    for i = 1, loopTimes do
      local randomCardId = matchedIds[math.random(1, #matchedIds)]
      table.insert(cardPack, randomCardId)
      table.removeOne(matchedIds, randomCardId)
    end
  end

  return cardPack
end

local guanyu = General(extension, "joy_mou__guanyu", "shu", 4)
local weilingy = fk.CreateViewAsSkill{
  name = "joy_weilingy",
  prompt = "#weilingy-viewas",
  pattern = "slash,analeptic",
  interaction = function()
    local names, all_names = {} , {}
    local pat = Fk.currentResponsePattern
    for _, id in ipairs(Fk:getAllCardIds()) do
      local card = Fk:getCardById(id, true)
      if (card.trueName == "slash" or card.trueName == "analeptic") and
      not card.is_derived and not table.contains(all_names, card.name) then
        table.insert(all_names, card.name)
        local to_use = Fk:cloneCard(card.name)
        if not Self:prohibitUse(to_use) then
          if pat == nil then
            if Self:canUse(card) then
              table.insert(names, card.name)
            end
          else
            if Exppattern:Parse(pat):matchExp(card.name) then
              table.insert(names, card.name)
            end
          end
        end
      end
    end
    if #names == 0 then return false end
    return UI.ComboBox { choices = names, all_choices = all_names }
  end,
  card_filter = function(self, to_select, selected)
    return #selected == 0
  end,
  view_as = function(self, cards)
    if #cards ~= 1 or not self.interaction.data then return end
    local card = Fk:cloneCard(self.interaction.data)
    card:addSubcard(cards[1])
    card.skillName = self.name
    return card
  end,
  before_use = function(self, player, use)
    local room = player.room
    use.extra_data = use.extra_data or {}
    use.extra_data.weilingy_user = player.id
  end,
  enabled_at_play = function(self, player)
    return player:usedSkillTimes(self.name) == 0
  end,
  enabled_at_response = function(self, player, response)
    return not response and player:usedSkillTimes(self.name) == 0
  end,
}
local weilingy_trigger = fk.CreateTriggerSkill{
  name = "#joy_weilingy_trigger",
  events = {fk.CardUsing,"fk.joy_weiling"},
  mute = true,
  can_trigger = function(self, event, target, player, data)
    if event == fk.CardUsing then
      return not player.dead and data.extra_data and data.extra_data.weilingy_user == player.id and data.card.color ~= Card.NoColor
    elseif event == "fk.joy_weiling" then
      return target == player and player:hasSkill(self)
    end
  end,
  on_cost = function(self, event, target, player, data)
    if event == fk.CardUsing then
      return true
    elseif event == "fk.joy_weiling" then
      return player.room:askForSkillInvoke(player,self.name,nil,"你可以获得一张【水淹七军】")
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    if event == fk.CardUsing then
      local to
      local color = data.card:getColorString()
      for _, pid in ipairs(TargetGroup:getRealTargets(data.tos)) do
        to = room:getPlayerById(pid)
        if not to.dead then
          local mark = to:getTableMark( "@joy_weilingy-turn")
          if table.insertIfNeed(mark, color) then
            room:setPlayerMark(to, "@joy_weilingy-turn", mark)
            to:filterHandcards()
          end
        end
      end
    elseif event == "fk.joy_weiling" then
      player.room:setPlayerMark(player,"@joy_weilings",0)
      room:notifySkillInvoked(player, self.name, "drawcard")
      local ids = getCards(room,"joy_shuiyan", 1)
      if #ids > 0 then
        room:obtainCard(player, ids[1], false, fk.ReasonPrey)
      end
    end
  end,
  refresh_events = {fk.CardUsing,fk.CardResponding},
  can_refresh =function (self, event, target, player, data)
    return target == player and player:hasSkill(self) and player:getMark("@joy_weilings") < 7
  end,
  on_refresh = function (self, event, target, player, data)
    player.room:addPlayerMark(player,"@joy_weilings",1)
    if player:getMark("@joy_weilings") >= 7 then
      player.room.logic:trigger("fk.joy_weiling", player)
    end
  end
}
local weilingy_filter = fk.CreateFilterSkill{
  name = "#joy_weilingy_filter",
  card_filter = function(self, to_select, player)
    if not table.contains(player.player_cards[Player.Hand], to_select.id) then return false end
    local mark = player:getTableMark("@joy_weilingy-turn")
    return table.contains(mark, to_select:getColorString())
  end,
  view_as = function(self, to_select)
    return Fk:cloneCard("slash", to_select.suit, to_select.number)
  end,
}
local duoshou = fk.CreateTriggerSkill{
  name = "joy__duoshou",
  anim_type = "drawcard",
  events = {fk.Damage,fk.TargetSpecified},
  frequency = Skill.Compulsory,
  can_trigger = function(self, event, target, player, data)
    if event == fk.Damage then
      return target == player and player:hasSkill(self) and
    table.contains(player:getTableMark("@joy_duoshou-turn"), "sanshou_damage") and data.to and not data.to:isNude() 
    elseif event == fk.TargetSpecified then
      if
      player:hasSkill(self) and
      target == player and
      data.card.trueName == "slash" and
      data.firstTarget and player:getMark(self.name.."-turn") == 0
    then
      local room = player.room
      local logic = room.logic
        local n = #logic:getEventsOfScope(GameEvent.UseCard,2, function (e)
          local use = e.data[1]
          if use.card.trueName == "slash" and use.from == target.id then
            return true
          end
          return false
        end, Player.HistoryTurn)
        
      return n == 1
    end
      return false
    end
  end,
  on_use = function(self, event, target, player, data)
    if event == fk.Damage then
      local mark = player:getTableMark("@joy_duoshou-turn")
      table.removeOne(mark, "sanshou_damage")
      player.room:setPlayerMark(player, "@joy_duoshou-turn", #mark > 0 and mark or 0)
      if data.to ~= data.from then
        local card = player.room:askForCardsChosen(player,data.to,1,1,"he",self.name,"选择 %src 一张牌获得:"..data.to.id)
        if #card > 0 then
          player.room:obtainCard(player,card,false,fk.ReasonPrey,player.id,self.name)
        end
      end
    elseif event == fk.TargetSpecified then
      player.room:setPlayerMark(player, self.name.."-turn",1)
      player:drawCards(2, self.name)
    end
  end,

  refresh_events = {fk.PreCardUse, fk.TurnStart, fk.EventAcquireSkill, fk.EventLoseSkill},
  can_refresh = function (self, event, target, player, data)
    if event == fk.EventAcquireSkill or event == fk.EventLoseSkill then
      return player == target and data == self
    else
      return player:hasSkill(self, true) and (event == fk.TurnStart or player == target)
    end
  end,
  on_refresh = function (self, event, target, player, data)
    local room = player.room
    if event == fk.PreCardUse then
      local mark = player:getTableMark("@joy_duoshou-turn")
      local update = false
      if data.card.color == Card.Red and table.removeOne(mark, "sanshou_red") then
        update = true
      end
      if data.card.type == Card.TypeBasic and table.removeOne(mark, "sanshou_basic") then
        update = true
        if player:hasSkill(self) then
          data.extraUse = true
        end
      end
      if update then
        room:setPlayerMark(player, "@joy_duoshou-turn", #mark > 0 and mark or 0)
      end
    elseif event == fk.TurnStart then
      room:setPlayerMark(player, "@joy_duoshou-turn", {"sanshou_red", "sanshou_basic", "sanshou_damage"})
    elseif event == fk.EventAcquireSkill then
      local turn_event = room.logic:getCurrentEvent():findParent(GameEvent.Turn, true)
      if turn_event == nil then return false end
      local a, b, c = true, true, true
      local use = nil
      player.room.logic:getEventsByRule( GameEvent.UseCard, 1, function (e)
        use = e.data[1]
        if use.from == player.id then
          if use.card.color == Card.Red then
            a = false
          end
          if use.card.type == Card.TypeBasic then
            b = false
          end
          return not (a or b)
        end
      end, turn_event.id)
      local mark = {}
      if a then
        table.insert(mark, "sanshou_red")
      end
      if b then
        table.insert(mark, "sanshou_basic")
      end
      room.logic:getActualDamageEvents(1, function (e)
        use = e.data[1]
        if use.from == player then
          c = false
          return true
        end
        return false
      end, nil, turn_event.id)
      if c then
        table.insert(mark, "sanshou_damage")
      end
      room:setPlayerMark(player, "@joy_duoshou-turn", #mark > 0 and mark or 0)
    elseif event == fk.EventLoseSkill then
      room:setPlayerMark(player, "@joy_duoshou-turn", 0)
    end
  end,
}
local duoshou_targetmod = fk.CreateTargetModSkill{
  name = "#joy_duoshou_targetmod",
  bypass_distances =  function(self, player, skill, card, to)
    return player:hasSkill(duoshou) and card and card.color == Card.Red and
    table.contains(player:getTableMark("@joy_duoshou-turn"), "sanshou_red")
  end,
}

weilingy:addRelatedSkill(weilingy_trigger)
weilingy:addRelatedSkill(weilingy_filter)
duoshou:addRelatedSkill(duoshou_targetmod)
guanyu:addSkill(weilingy)
guanyu:addSkill(duoshou)

Fk:loadTranslationTable{
  ["joy_mou__guanyu"] = "谋关羽",
  ["#joy_mou__guanyu"] = "威震华夏",
  ["joy_weilingy"] = "威临",
  [":joy_weilingy"] = "每回合限一次，你可以将一张牌当任意一种【杀】或【酒】使用。"..
  "以此法使用的牌指定目标后，你令其与此牌颜色相同的手牌均视为【杀】直到回合结束。<br>每当你累计使用或打出7张及以上的牌后，你可以获得一张【水淹七军】。",
  ["joy__duoshou"] = "夺首",
  [":joy__duoshou"] = "锁定技，每回合你首次使用红色牌无距离关系的限制、首次使用基本牌不计入限制的次数、首次造成伤害后获得其一张牌、首次使用【杀】指定目标后摸两张牌。",
  ["@joy_weilings"] = "水淹",
  ["#joy_weilingy_trigger"] = "威临",
  ["#joy_weilingy_filter"] = "威临",
  ["@joy_weilingy-turn"] = "威临",
  ["@joy_duoshou-turn"] = "夺首",
  ["sanshou_red"] = "红",
  ["sanshou_basic"] = "基",
  ["sanshou_damage"] = "伤",

}

local jizhi = fk.CreateTriggerSkill{
  name = "joy_mou__jizhi",
  anim_type = "drawcard",
  frequency = Skill.Compulsory,
  events = {fk.CardUsing},
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(self) and data.card.type == Card.TypeTrick
  end,
  on_use = function(self, event, target, player, data)
    player:drawCards(1,self.name)
  end,
}
local jizhi_targetmod = fk.CreateTargetModSkill{
  name = "#joy_mou__jizhi_targetmod",
  main_skill = jizhi,
  frequency = Skill.Compulsory,
  bypass_distances = function(self, player, skill, card)
    return player:hasSkill(jizhi) and card and card.type == Card.TypeTrick
  end,
}
jizhi:addRelatedSkill(jizhi_targetmod)
Fk:loadTranslationTable{
  ["joy_mou__jizhi"] = "集智",
  [":joy_mou__jizhi"] = "锁定技，当你使用锦囊牌时，你摸一张牌；你使用锦囊牌无距离限制。",
  ["#joy_mou__jizhi_targetmod"] = "集智",
}

local qicai = fk.CreateActiveSkill{
  name = "joy_mou__qicai",
  anim_type = "switch",
  switch_skill_name = "joy_mou__qicai",
  card_num = function ()
    return Self:getSwitchSkillState("joy_mou__qicai", false) ~= fk.SwitchYang and 1 or 0
  end,
  target_num = 0,
  prompt = function ()
    return Self:getSwitchSkillState("joy_mou__qicai", false) == fk.SwitchYang and "令你使用的下一张普通锦囊牌可增加或减少一个目标" or "你可以弃置一张基本牌，获得一张锦囊牌"
  end,
  can_use = function ()
    if Self:getSwitchSkillState("joy_mou__qicai", false) == fk.SwitchYang then
      return Self:getMark("joy_mou__qicai1-turn") < 2
    else
      return Self:getMark("joy_mou__qicai2-turn") < 2
    end
  end,
  card_filter = function (self, to_select, selected)
    if Self:getSwitchSkillState("joy_mou__qicai", false) == fk.SwitchYang then
      return false
    else
      return #selected == 0 and Fk:getCardById(to_select).type == Card.TypeBasic
    end
  end,
  target_filter = function(self, to_select, selected)
    return false
  end,
  on_use = function(self, room, effect)
    local player = room:getPlayerById(effect.from)
    local switch = player:getSwitchSkillState(self.name, true,false)
    if switch == fk.SwitchYang then
      room:addPlayerMark(player,"joy_mou__qicai1-turn",1)
      room:setPlayerMark(player,"@@joy_mou__qicai",1)
    else
      room:addPlayerMark(player,"joy_mou__qicai2-turn",1)
      room:throwCard(effect.cards,self.name,player,player)
      if not player.dead then
        local cards = room:getCardsFromPileByRule(".|.|.|.|.|trick",1,"allPiles")
        if #cards > 0 then
        room:moveCards({
        ids = cards,
        to = player.id,
        toArea = Card.PlayerHand,
        moveReason = fk.ReasonJustMove,
        proposer = player.id,
        skillName = self.name,
        })
        end
      end
    end
  end,
}
local qicai_delay = fk.CreateTriggerSkill{
  name = "#joy_mou__qicai_delay",
  events = {fk.GameStart},
  mute = true,
  can_trigger = function(self, event, target, player, data)
    return player:hasSkill(qicai)
  end,
  on_cost = Util.TrueFunc,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local choice = player.room:askForChoice(player,{"joy_mou__qicai1","joy_mou__qicai2"},qicai.name,"选择初始状态",true)
    if not choice then
      choice = table.random({"joy_mou__qicai1","joy_mou__qicai2"})
    end
    if choice == "joy_mou__qicai1" then
      room:notifySkillInvoked(player,qicai.name)
      --room:delay(200)
      player.room:setPlayerMark(player, MarkEnum.SwithSkillPreName .. qicai.name,fk.SwitchYang)
      player:setSkillUseHistory(qicai.name, 0, Player.HistoryGame)
    elseif choice == "joy_mou__qicai2" then
      room:notifySkillInvoked(player,qicai.name)
      --room:delay(200)
      player.room:setPlayerMark(player, MarkEnum.SwithSkillPreName .. qicai.name,fk.SwitchYin)
      player:setSkillUseHistory(qicai.name, 0, Player.HistoryGame)
    end
  end,
  refresh_events = {fk.TargetConfirming},
  can_refresh = function (self, event, target, player, data)
    return player.id == data.from and player:getMark("@@joy_mou__qicai") > 0 and data.card and data.card:isCommonTrick()
  end,
  on_refresh = function (self, event, target, player, data)
    local room = player.room
    room:setPlayerMark(player,"@@joy_mou__qicai",0)
    room:notifySkillInvoked(player, qicai.name,"offensive")
    player:broadcastSkillInvoke(qicai.name)
    local targets = player.room:getUseExtraTargets( data, true, true)
        local origin_targets = U.getActualUseTargets(room, data, event)
        if #origin_targets > 1 then
          table.insertTable(targets, origin_targets)
        end
        if #targets > 0 then
          local tos = player.room:askForChoosePlayers(player,targets, 1,1,
            "你可以为"..data.card:toLogString().."增加或减少一个目标",qicai.name, true)
          if #tos > 0 then
            local tos1,tos2 = {},{}
            for _, pid in ipairs(tos) do
              if table.contains(AimGroup:getAllTargets(data.tos),pid) then
                table.insertIfNeed(tos1,pid)
              else
                table.insertIfNeed(tos2,pid)
              end
            end
            if #tos1 > 0 then
              for _, pid in ipairs(tos1) do
                AimGroup:cancelTarget(data,pid)
              end
            end
            if #tos2 > 0 then
                AimGroup:addTargets(player.room, data,tos2)
            end
          end
        end
  end,
}
qicai:addRelatedSkill(qicai_delay)
Fk:loadTranslationTable{
  ["joy_mou__qicai"] = "奇才",
  ["#joy_mou__qicai_delay"] = "奇才",
  ["joy_mou__qicai1"] = "奇才：阳",
  [":joy_mou__qicai1"] = "令你使用的下一张普通锦囊牌可增加或减少一个目标",
  ["joy_mou__qicai2"] = "奇才：阴",
  [":joy_mou__qicai2"] = "你可以弃置一张基本牌，获得一张锦囊牌",
  [":joy_mou__qicai"] = "转换技，游戏开始时可自选阴阳状态。"..
  "<br>阳：每回合限两次，令你使用的下一张普通锦囊牌可增加或减少一个目标。"..
  "<br>阴：每回合限两次，你可以弃置一张基本牌，获得一张锦囊牌。",
  ["@@joy_mou__qicai"] = "奇才"
}

--流马区相关

---@param room Room @ 房间
---@return integer[]
local GetNMPile = function(room)
  local cards = room.tag["joy_niuma"] or {}
  room.tag["joy_niuma"] = table.filter(cards, function (id)
    return room:getCardArea(id) == Card.Void
  end)
  return table.simpleClone(room.tag["joy_niuma"])
end

---@param room Room @ 房间
local NotifyNMPile = function(room)
  local tars1 = {}
  local tars2 = {}
  for _, p in ipairs(room.alive_players) do
    if p:hasSkill("joy_mou__niuma",true,true) or p:hasSkill("joy_mou__niumaget",true,true) then
      table.insertIfNeed(tars1,p)
    else
      table.insertIfNeed(tars2,p)
    end
  end
  local log1 = {
    type = "“流马”区现有 %arg 张牌 %card",
    arg = #GetNMPile(room),
    card = GetNMPile(room),
  }
  local log2 = {
    type = "“流马”区现有 %arg 张牌",
    arg = #GetNMPile(room),
  }
  room:doBroadcastNotify("GameLog",json.encode(log1),tars1)
  room:doBroadcastNotify("GameLog",json.encode(log2),tars2)
  AbstractRoom.setBanner(room,"@$joy_niuma_cards",table.simpleClone(room.tag["joy_niuma"]))
  AbstractRoom.setBanner(room,"joy_niuma_num",#table.simpleClone(room.tag["joy_niuma"]))
  room:doBroadcastNotify("SetBanner", json.encode{ "@$joy_niuma_cards",table.simpleClone(room.tag["joy_niuma"]) },tars1)
  room:doBroadcastNotify("SetBanner", json.encode{ "@joy_niuma_num",#table.simpleClone(room.tag["joy_niuma"]) },tars2)
  for _, p in ipairs(tars1) do
    room:setPlayerMark(p,"joy_niuma",table.simpleClone(room.tag["joy_niuma"]))
  end
end
Fk:loadTranslationTable{
  ["@$joy_niuma_cards"] = "流马",
  ["@joy_niuma_num"] = "流马",
}
---@param room Room @ 房间
---@param card integer|integer[]|Card|Card[] @ 要加入流马区的牌/id/intList
---@param skillName string @ 移动的技能名
---@param proposer integer @ 移动操作者的id
local AddToNMPile = function(room, card, skillName, proposer)
  local tars1 = {}
  local tars2 = {}
  for _, p in ipairs(room.alive_players) do
    if p:hasSkill("joy_mou__niuma",true,true) or p:hasSkill("joy_mou__niumaget",true,true) then
      table.insertIfNeed(tars1,p)
    else
      table.insertIfNeed(tars2,p)
    end
  end
  local ids = Card:getIdList(card)
  room.tag["joy_niuma"] = room.tag["joy_niuma"] or {}
  local add, remove = {}, {}
  local ren_cards = table.simpleClone(room.tag["joy_niuma"])
  local ren_limit = 5
  for i = 1, ren_limit do
    local id = ids[i]
    if not id then break end
    table.insert(ren_cards, id)
    table.insert(add, id)
  end
  if #ren_cards > ren_limit then
    for i = #ren_cards - ren_limit, 1, -1 do
      table.insert(remove, table.remove(room.tag["joy_niuma"], i))
    end
  end
  local moveInfos = {}
  if #add > 0 then
    table.insertTable(room.tag["joy_niuma"], add)
    table.insert(moveInfos, {
      ids = add,
      from = room.owner_map[add[1]],
      toArea = Card.Void,
      moveReason = fk.ReasonJustMove,
      skillName = skillName,
      moveVisible = false,
      proposer = proposer,
      visiblePlayers = table.map(tars1,Util.IdMapper),
    })
    local log1 = {
      type = "%arg 张牌被移入“流马”区 %card",
      arg = #add,
      card = add,
    }
    local log2 = {
      type = "%arg 张牌被移入“流马”区",
      arg = #add,
    }
    room:doBroadcastNotify("GameLog", json.encode(log1),tars1)
    room:doBroadcastNotify("GameLog", json.encode(log2),tars2)
  end
  if #remove > 0 then
    local info = {
      ids = remove,
      toArea = Card.DiscardPile,
      moveReason = fk.ReasonPutIntoDiscardPile,
      skillName = "流马",
      moveVisible = true,
    }
    table.insert(moveInfos, info)
    room:sendLog{
      type = "%arg 张牌从“牛马”区溢出 %card",
      arg = #remove,
      card = remove,
    }
  end
  if #moveInfos > 0 then
    room:moveCards(table.unpack(moveInfos))
  end
  NotifyNMPile(room)
end



local niumaget = fk.CreateViewAsSkill{
  name = "joy_mou__niumaget",
  pattern = ".",
  expand_pile = function() 
    return Self:getTableMark("joy_niuma")
  end,
  card_filter = function(self, to_select, selected)
    if #selected == 0 then
      for _, cid in ipairs(Self:getTableMark("joy_niuma")) do
        if cid == to_select then
          local card = Fk:getCardById(to_select)
          if Fk.currentResponsePattern == nil then
            return Self:canUse(card) and not Self:prohibitUse(card)
          else
            return Exppattern:Parse(Fk.currentResponsePattern):match(card)
          end
        end
      end
    end
  end,
  view_as = function(self, cards)
    if #cards ~= 1 then return end
    return Fk:getCardById(cards[1])
  end,
  enabled_at_play = function(self, player)
    local mark = player:getTableMark("joy_niuma")
    for _, cid in ipairs(mark) do
      local to_use = Fk:cloneCard(Fk:getCardById(cid).name)
      to_use.skillName = self.name
      if player:canUse(to_use) and not player:prohibitUse(to_use) then
        return true
      end
    end
    return false
  end,
  enabled_at_response = function(self, player, response)
    local mark = player:getTableMark("joy_niuma")
    if not response then
      for _, cid in ipairs(mark) do
        local to_use = Fk:cloneCard(Fk:getCardById(cid).name)
        to_use.skillName = self.name
        if Fk.currentResponsePattern and Exppattern:Parse(Fk.currentResponsePattern):match(to_use) and
            not player:prohibitUse(to_use)  then
          return true
        end
      end
    else
      for _, cid in ipairs(mark) do
        local to_use = Fk:cloneCard(Fk:getCardById(cid).name)
        to_use.skillName = self.name
        if Fk.currentResponsePattern and Exppattern:Parse(Fk.currentResponsePattern):match(to_use)  then
          return true
        end
      end
    end
    return false
  end,
}
local niumaget_trigger = fk.CreateTriggerSkill{
  name = "#joy_mou__niumaget_trigger",
  events = {fk.EventPhaseEnd},
  can_trigger = function (self, event, target, player, data)
    if target ~= player or not player:hasSkill(niumaget) then return end
    if event == fk.EventPhaseEnd and player.phase == Player.Play  then
      local cards = player.room.tag["joy_niuma"] or {}
      return not player:isKongcheng() and #cards < 5 and player.hp > 0
    end
  end,
  on_cost = function (self, event, target, player, data)
    local room = player.room
    if event == fk.EventPhaseEnd then
      local cards = player.room.tag["joy_niuma"] or {}
      local n = math.min(player.hp,5 - #cards)
      local card = room:askForCard(player,1,n,false,self.name,true,".","你可将至多"..(n).."张手牌扣置于“流马”区")
      if #card > 0 then
        self.cost_data = card
        return true
      end
    end
  end,
  on_use = function (self, event, target, player, data)
    local room = player.room
    if event == fk.EventPhaseEnd then
      AddToNMPile(room,self.cost_data, self.name, player.id)
    end
  end,
}
niumaget:addRelatedSkill(niumaget_trigger)
Fk:loadTranslationTable{
  ["joy_mou__niumaget"] = "流马",
  [":joy_mou__niumaget"] = "出牌阶段结束时，你可将至多X张手牌扣置于“流马”区（X为你当前体力值，“流马”区的牌至多5张）；你可将“流马”区的牌正常使用或打出。"..
  "<br/><font color='grey'>#\"<b>流马区</b>\"<br/>"..
  "流马区是一个存于场上，用于存放牌的公共区域，上限为5张牌，正常玩家无法看到扣置于其中的牌。",
  ["#joy_mou__niumaget_trigger"] = "流马",
}
local niuma = fk.CreateViewAsSkill{
  name = "joy_mou__niuma",
  pattern = ".",
  expand_pile = function() 
    return Self:getTableMark("joy_niuma")
  end,
  card_filter = function(self, to_select, selected)
    if #selected == 0 then
      for _, cid in ipairs(Self:getTableMark("joy_niuma")) do
        if cid == to_select then
          local card = Fk:getCardById(to_select)
          if Fk.currentResponsePattern == nil then
            return Self:canUse(card) and not Self:prohibitUse(card)
          else
            return Exppattern:Parse(Fk.currentResponsePattern):match(card)
          end
        end
      end
    end
  end,
  view_as = function(self, cards)
    if #cards ~= 1 then return end
    return Fk:getCardById(cards[1])
  end,
  enabled_at_play = function(self, player)
    local mark = player:getTableMark("joy_niuma")
    for _, cid in ipairs(mark) do
      local to_use = Fk:cloneCard(Fk:getCardById(cid).name)
      to_use.skillName = self.name
      if player:canUse(to_use) and not player:prohibitUse(to_use) then
        return true
      end
    end
    return false
  end,
  enabled_at_response = function(self, player, response)
    local mark = player:getTableMark("joy_niuma")
    if not response then
      for _, cid in ipairs(mark) do
        local to_use = Fk:cloneCard(Fk:getCardById(cid).name)
        to_use.skillName = self.name
        if Fk.currentResponsePattern and Exppattern:Parse(Fk.currentResponsePattern):match(to_use) and
            not player:prohibitUse(to_use)  then
          return true
        end
      end
    else
      for _, cid in ipairs(mark) do
        local to_use = Fk:cloneCard(Fk:getCardById(cid).name)
        to_use.skillName = self.name
        if Fk.currentResponsePattern and Exppattern:Parse(Fk.currentResponsePattern):match(to_use)  then
          return true
        end
      end
    end
    return false
  end,
}
local niuma_trigger = fk.CreateTriggerSkill{
  name = "#joy_mou__niuma_trigger",
  events = {fk.RoundStart,fk.EventPhaseEnd},
  can_trigger = function (self, event, target, player, data)
    if  not player:hasSkill(niuma) then return end
    if event == fk.RoundStart then
      local room = player.room
      for _, p in ipairs(room:getOtherPlayers(player)) do
        if p:hasSkill(niuma,true) or p:hasSkill(niumaget,true) then
          return false
        end
      end
      return true
    elseif event == fk.EventPhaseEnd and target == player and player.phase == Player.Play  then
      local cards = player.room.tag["joy_niuma"] or {}
      return not player:isKongcheng() and #cards < 5 and player.hp > 0
    end
  end,
  on_cost = function (self, event, target, player, data)
    local room = player.room
    if event == fk.RoundStart then
      local tar = room:askForChoosePlayers(player,table.map(room:getOtherPlayers(player),Util.IdMapper),1,1,"你可令一名其他角色获得〖流马〗",self.name,true)
      if #tar > 0 then
        self.cost_data = tar[1]
        return true
      end
    elseif event == fk.EventPhaseEnd then
      local cards = player.room.tag["joy_niuma"] or {}
      local n = math.min(player.hp,5 - #cards)
      local card = room:askForCard(player,1,n,false,self.name,true,".","你可将至多"..(n).."张手牌扣置于“流马”区")
      if #card > 0 then
        self.cost_data = card
        return true
      end
    end
  end,
  on_use = function (self, event, target, player, data)
    local room = player.room
    if event == fk.RoundStart then
      room:handleAddLoseSkills(room:getPlayerById(self.cost_data),"joy_mou__niumaget")
    elseif event == fk.EventPhaseEnd then
      AddToNMPile(room,self.cost_data, self.name, player.id)
    end
  end,
  refresh_events = {fk.AfterCardsMove,fk.AfterPlayerRevived,fk.EventAcquireSkill},
  can_refresh = function(self, event, target, player, data)
    if event == fk.AfterCardsMove then
      if player.seat == 1 and player.room.tag["joy_niuma"] then
        for _, move in ipairs(data) do
          if move.toArea ~= Card.Void then
            for _, info in ipairs(move.moveInfo) do
              if table.contains(player.room.tag["joy_niuma"], info.cardId) then
                return true
              end
            end
          end
        end
      end
    elseif event == fk.AfterPlayerRevived then
      return target == player and (player:hasSkill(niuma.name,true,true) or player:hasSkill("joy_mou__niumaget",true,true))
    else
      return target == player and table.contains({"joy_mou__niuma","joy_mou__niumaget"},data.name) and player:hasSkill(data.name,true)
    end
  end,
  on_refresh = function(self, event, target, player, data)
    local room = player.room
    if event == fk.AfterCardsMove then
      for _, move in ipairs(data) do
        if move.toArea ~= Card.Void then
          for _, info in ipairs(move.moveInfo) do
            if table.contains(room.tag["joy_niuma"], info.cardId) then
              NotifyNMPile(room)
            end
          end
        end
      end
    else
      local mark = room.tag["joy_niuma"] or {}
      room:setPlayerMark(player,"joy_niuma",mark)
    end
    
  end,
}
niuma:addRelatedSkill(niuma_trigger)
Fk:loadTranslationTable{
  ["joy_mou__niuma"] = "流马",
  [":joy_mou__niuma"] = "①出牌阶段结束时，你可将至多X张手牌扣置于“流马”区（X为你当前体力值，“流马”区的牌至多5张）；你可将“流马”区的牌正常使用或打出。"..
  "<br>②每轮开始时，若场上仅有你拥有〖流马〗，你可令一名其他角色获得〖流马〗。"..
  "<br/><font color='grey'>#\"<b>流马区</b>\"<br/>"..
  "流马区是一个存于场上，用于存放牌的公共区域，上限为5张牌，正常玩家无法看到扣置于其中的牌。",
  ["#joy_mou__niuma_trigger"] = "流马",
}
local huangyueying = General(extension, "joy_mou__huangyueying", "shu", 3)
huangyueying:addSkill(jizhi)
huangyueying:addSkill(qicai)
huangyueying:addSkill(niuma)
huangyueying:addRelatedSkill(niumaget)
Fk:loadTranslationTable{
  ["joy_mou__huangyueying"] = "谋黄月英",
}
return extension
